Ashok Mahalik
Ashok Mahalik

Reputation: 51

Does Ethereum Solidity support Associative Arrays?

For example - Arrays with named indexes or hashes. Something like PHP code;

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

Thanks

Upvotes: 3

Views: 1359

Answers (2)

Rob Hitchens
Rob Hitchens

Reputation: 1059

Solidity supports something called a struct that creates a new type from existing types. These can be passed around between functions internally, but as yet not between contracts and the outside world.

Just adding to what Jacob said, you can store structs in a mapping (a hash table):

mapping(address => MyStruct) structsInMap;

or in arrays:

MyStruct[] structsInList;

Here's a little example that passes values around observing fixed-size rules compatible with the 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);
    }
}

And Browser Solidity showing struct vals coming back after the constructor set them.

enter image description here

Hope it helps.

Upvotes: 3

Jacob
Jacob

Reputation: 43269

Solidity supports a type called 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

Upvotes: 2

Related Questions