I'm trying to understand how mappings work. I've never seen anything like it before, but I'm sure many languages use something similar. Anyway, here's my code:
What am I doing wrong here?
Thank you!
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityI'm trying to understand how mappings work. I've never seen anything like it before, but I'm sure many languages use something similar. Anyway, here's my code:
What am I doing wrong here?
Thank you!
The reason for you error is because in solidity you can only have declarations outside functions.
In you code, you declare the mapping and then in another operation you do an assignment which is only possible in a function.
For the other data types its possible also to do the assignment during initialization so it works.
Mappings can be thought of as Hash tables but it is different. In solidity a mapping is from start initialized with all possible keys and the associated value of the key is the default for the specified type. So in solidity you can only add new values to keys and you cannot add new keys since they are already there.
Also to mention that by default you cannot iterate over a mapping in Solidity. Again that is related to what I wrote earlier. Also you cannot retrieve only the keys for which you set up some values because you have all the keys set up by default with values.
ValueType
.
Jun 12, 2017 at 23:15
Mappings are only marginally like hash tables, and are implemented totally unlike any other programming language. Typically a hash table would have an internal array that is 25-75% full of keys/values you have stored. And you can do things like iterate over them, as you're only skipping at most 75% empty cells in a non-trivial table. Ways Solidity mappings are different:
O(1)
operations (from the script's POV), not O(1+e)
like most other hash tables. There are no long-tail growth costs, as the table never expands, nor any O(n)
collision chain walks.So I'd recommend NOT thinking of them like hash tables. Instead think of them only as one-way functions that returns a pointer to a pseudo-random memory address.
To understand mappings, you can see them as Hash tables.
About your code, probably someone else can give you a complete explanation, but I think it's because you have to assign the value to the mapping inside a function, for example:
contract Complex{
uint a = 1;
uint b = 3;
mapping(uint => uint) myMap;
function Complex(){
myMap[a] = b;
}
}
This piece of code is doing the same thing but putting the myMap[a] = b;
inside the constructor.