solidity개발시 gas비용을 최소화하기 위해 연산을 줄이는 것이 중요하다.


그래서 가장 유용한 data Type은 mapping인데,

mapping안에 array를 넣는 방법도 꽤 추천할 만하지만


array의 길이가 길어진다면 O(n)의 서칭이 발생하므로,

데이타가 많다면 mapping안에 mapping을 또 넣는 방법이 좋을 것 같다.


일반적인 language용어로 말하자면, 

hashMap안에 또 hashMap을 넣는 것이다.


단, 이를 조회하려면 parentKey와 childKey모두 알아야 조회가 가능하다.


예제는 다음과 같다. 참고사이트: REF


contract SampleContract {

  struct ChildStruct {
    bool isPresent;
    bytes32 name;
  }

  struct ParentStruct {
    bool isPresent;
    bytes32 name;
    mapping (bytes32 => ChildStruct) childStructs; 
  }

  mapping(bytes32 => ParentStruct) public parentStructs;

  function insertData(
    bytes32 parentKey, 
    bytes32 parentName, 
    bytes32 childKey, 
    bytes32 childName)
    public 
    returns(bool success)
  {

    parentStructs[parentKey].isPresent = true;
    parentStructs[parentKey].name = parentName;
    parentStructs[parentKey].childStructs[childKey].isPresent = true;
    parentStructs[parentKey].childStructs[childKey].name = childName;
    return true;
  }

  function getChild(bytes32 parentKey, bytes32 childKey) public constant returns(bool isPresent, bytes32 name) {
    return (parentStructs[parentKey].childStructs[childKey].isPresent, parentStructs[parentKey].childStructs[childKey].name);
  }

}


Posted by yongary
,