Maps in any form are usually are core feature of any language or its standard library. No matter whether they are called HashMap (backed by a hash table) or TreeMap (backed by a tree), they are an essential part of many algorithms. They are the goto data structure when you want to map a key to a value.
Solidity also has a map type, but it's not a complex type like in many other languages, it's actually a primitive and is called mapping
.
The Mapping Type
Solidity's mapping type is straightforward to declare and use:
mapping(keyType => valueType) variableIdentifier;
You don't even need to assign anything. The default value of a variable declared as mapping
is already a fully initialized map.
If you want to add a value to your map, you can use the same syntax you might already be comfortable with from handling JavaScript objects:
myMapping[key] = value;
Yep, that's it. It's that simple.
And reading from it is equally as straightforward:
valueType value = myMapping[key];
A Mapping Use Case
You might ask yourself what you can actually use Solidity's map for. Well, whenever you want to store the relation between a key and a value.
ERC20 tokens, for example, store the balance of their coin holders in mappings, like in the example below:
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
contract MyToken {
mapping(address => uint) private _balances;
function balance() public view returns (uint) {
return _balances[msg.sender];
}
function addFunds(address to, uint amount) public {
_balances[to] += amount;
}
}
Before You Leave
If you would love to read even more content like this, feel free to visit me on Twitter or LinkedIn.
I'd love to count you as my ever-growing group of awesome friends!