Solidity

映射不適用於地址類型

  • October 23, 2018

以下程式碼有效,即我可以呼叫add(2,3)然後get(2,0)返回 3:

pragma solidity ^0.4.10;

contract Bar {
   struct Foo{
       uint x;
   }
   mapping(uint => Foo[]) foo;

   function add(uint id, uint _x) public {
       foo[id].push(Foo(_x));
   }

   function get(uint id, uint index) view public returns(uint){
       return foo[id][index].x;
   }
}

這段程式碼不起作用,就是我呼叫add(0xB139e6071772FAdC0e1Ad79C63415a2866fD447F,3),然後get(0xB139e6071772FAdC0e1Ad79C63415a2866fD447F,0)返回0

pragma solidity ^0.4.10;

contract Bar {
   struct Foo{
       uint x;
   }
   mapping(address => Foo[]) foo;

   function add(address id, uint _x) public {
       foo[id].push(Foo(_x));
   }

   function get(address id, uint index) view public returns(uint){
       return foo[id][index].x;
   }
}

唯一的區別是 uint 類型已經在幾個地方與地址類型交換了。

正如 smarx 所說,使用 remix 時必須用雙引號將地址括起來

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