Understanding Mapping in Solidity
Mappings is used in almost every solidity code you come across, and understanding how it works can be tricky. This article tries to explain it in a simple way.
Mapping works like a key-value store but, they don't store data in a sequential or graphical way like an array. Below is a simplified explanation:
How a mapping
Works Internally
A mapping(address => bool)
is a data structure where:
The key is an
address
.The value is a
bool
(in this case,true
orfalse
).
When you access a key (e.g., users[0x123...]
), the mapping:
Looks for the hashed key (address) in storage.
Returns the value (
true
orfalse
).
Conceptual Graphical Representation
Let’s assume the mapping looks like this:
mapping(address => bool) public users;
If users add their addresses like:
users[0x123...] = true;
users[0x456...] = true;
It can conceptually look like this:
Key (Address) | Value (bool) |
0x123... | true |
0x456... | true |
0x789... | false (default) |
Key Characteristics of a mapping
Non-Iterative:
- Unlike arrays, you cannot loop through or list all keys and values in a
mapping
. Solidity mappings are not iterable by design.
- Unlike arrays, you cannot loop through or list all keys and values in a
Default Value:
- Any key not explicitly set defaults to the value of
false
(or the default value of the mapping's value type).
- Any key not explicitly set defaults to the value of
Efficient Lookup:
- Mappings are optimized for lookups. Checking if
users[0x123...]
istrue
happens quickly, regardless of how many entries exist.
- Mappings are optimized for lookups. Checking if
Graphical Metaphor: A Big Locker System
Imagine a locker system with infinite lockers (keys):
If a locker (
0x123...
) is assigned, it containstrue
(or whatever value you set).If you check an unassigned locker, it’s empty (
false
by default).
Lockers (Addresses): [ 0x123, 0x456, 0x789, ... ]
Values (Bool): [ true, true, false, ... ]
Thanks for reading.