15

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?

21

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 braket notation, not dots.

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;
    }
}
  • 1
    Yep indeed i've just realized that i was coming here to answer my own question. Thanks you for the help! – jayD Feb 18 '16 at 2:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.