22

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?

1 Answer 1

32

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;
    }
}
2
  • 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, 2016 at 2:07
  • 1
    Is there a way to return the whole array ?
    – gneric
    Feb 4, 2022 at 9:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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