Understanding Mapping in Solidity

·

2 min read

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 or false).

When you access a key (e.g., users[0x123...]), the mapping:

  1. Looks for the hashed key (address) in storage.

  2. Returns the value (true or false).

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

  1. Non-Iterative:

    • Unlike arrays, you cannot loop through or list all keys and values in a mapping. Solidity mappings are not iterable by design.
  2. Default Value:

    • Any key not explicitly set defaults to the value of false (or the default value of the mapping's value type).
  3. Efficient Lookup:

    • Mappings are optimized for lookups. Checking if users[0x123...] is true happens quickly, regardless of how many entries exist.

Graphical Metaphor: A Big Locker System

Imagine a locker system with infinite lockers (keys):

  • If a locker (0x123...) is assigned, it contains true (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.