Ethereum Solidity是否支持关联数组?

时间:2017-01-27 12:47:17

标签: blockchain ethereum solidity

例如 - 具有命名索引或散列的数组。类似PHP代码的东西;

$array = array(
"foo" => "some foo value",
"bar" => "some bar value",);

由于

2 个答案:

答案 0 :(得分:2)

Solidity支持一种名为mapping的类型:

contract MappingExample {
    mapping(address => uint) public balances;

    function update(uint newBalance) {
        balances[msg.sender] = newBalance;
    }
}

http://solidity.readthedocs.io/en/develop/types.html#mappings

答案 1 :(得分:2)

Solidity支持一种称为结构的东西,它从现有类型中创建一个新类型。这些可以在内部函数之间传递,但在契约和外部世界之间尚未传递。

只需添加Jacob所说的内容,就可以将结构存储在映射(哈希表)中:

mapping(address => MyStruct) structsInMap;

或在数组中:

MyStruct[] structsInList;

这里有一个小例子,它围绕观察与ABI兼容的固定大小规则传递值。

contract StructExample {

    struct MyStruct {
        bool isMyStruct;
        uint amount;
        address[3] addressList;
        bytes32 name;
    }

    // storage instance of MyStruct
    MyStruct myStruct;

    function StructExample(
        uint amount, 
        address address1, 
        address address2, 
        address address3,
        bytes32 name) 
    {
        myStruct.isMyStruct = true;
        myStruct.amount = amount;
        myStruct.addressList = [address1, address2, address3];
        myStruct.name = name;
    }

    function getMyStruct() 
      constant
      returns(
          bool isMyStruct,
          uint amount,
          address[3] addressList,
          bytes32 name)
    {
        return (
            myStruct.isMyStruct, 
            myStruct.amount, 
            myStruct.addressList, 
            myStruct.name);
    }
}

浏览器Solidity显示构造函数设置后返回的结构。

enter image description here

希望它有所帮助。