Solidity

如何定義動態結構“欄位”?

  • May 4, 2018

我們有一個struct如下:

struct ObjectStruct {
       bytes32 state;
       address owner; 
       bool isObject;
   }
mapping(bytes32 => ObjectStruct) public objectStructs;
   bytes32[] public objectList;

現在,我們想要修改bytes32 state;欄位,使其成為動態的,這樣我們就可以向它“添加”幾個“sub_state”,例如。objectStructs[_object_id].state.location = _location;objectStructs[_object_id].state.price= _price;等等。

我們如何定義這樣一個“動態狀態欄位”,以便我們能夠向其中添加任何“sub_state”?

我將其定義如下:

struct ObjectStruct {
       bytes32 location;
       bytes32[] state;
       address owner; 
       bool isObject;
   }

進而 :

function newObject(bytes32 _object_id, bytes32 _state, address _owner) public returns(bool success) {
       require(!isObject(_object_id));

       objectStructs[_object_id].state = _state;
       objectStructs[_object_id].owner = _owner;
       objectStructs[_object_id].isObject = true;
       objectList.push(_object_id);

       LogNewObject(msg.sender, _object_id, _state, _owner);
       return true;
   }

event LogNewObject(address sender, bytes32 _object_id, bytes32 state, address owner);

然後,我們呼叫function newObject如下:

newObject(100, "location:Paris,price:50,sold:yes", '0xE07b6e5a2026CC916A4E2Beb03767ae0ED6af773');

我錯了 ?

正如您在文章中解釋的那樣,沒有這樣的*“動態狀態欄位” 。*但是您可以在結構內使用映射來為您完成此操作。

struct StateStruct {
   bytes32 description;
   mapping(bytes32 => bytes32) sub_state;
}

struct ObjectStruct {
   StateStruct state;
   address owner; 
   bool isObject;
}

然後使用

objectStructs[id].state.sub_state["location"] = "Paris";
objectStructs[id].state.sub_state["sold"] = "Yes";
objectStructs[id].state.sub_state["price"] = 50;

引用自:https://ethereum.stackexchange.com/questions/47529