Solidity – Using Arrays as Key or Value in Mapping

contract-developmentmappingsolidity

Is it possible to do a mapping with an Array as key/value ? Where an array would exist for each value ?

I'm actually looking to store structs in a mapping but can't seem to have it work.

Struct Foo{
uint x
}

mapping(uint => Foo[])foo; and even simply
mapping([] => uint)foo / (uint => [])foo; don't seems to work.

something so i can do :

foo.1.push(FooInstance)

foo.1[0] = FooInstance

Solidity Doc reads

Mapping types are declared as mapping _KeyType => _ValueType, where _KeyType can be almost any type except for a mapping and _ValueType can actually be any type, including mappings.

So aren't array considered a data type in solidity?

Best Answer

Mappings can only use elementary types (address, uint, bytes, string) as keys, and more specifically any type for which sha3() is defined. This means structs and arrays currently can't be used as keys.

mapping(uint => Foo[]) foo; should work, and does for me. Your code has some syntax errors, which might be the problem (struct shouldn't be capitalized, uint x needs a semicolon)

[] is not a type, you need some elementary type in front of it, like uint[].

Elements in arrays are accessed with bracket notation, not dot notation.

This contract should work:

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) public returns(uint){
        return foo[id][index].x;
    }
}
Related Topic