[Ethereum] How assignment to a mapping work

contract-developmentmappingsolidity

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:

enter image description here

What am I doing wrong here?

Thank you!

Best Answer

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.

Related Topic