0
0
BlockchainConceptBeginner · 3 min read

What is Mapping in Solidity: Explanation and Example

In Solidity, a mapping is a key-value data structure that stores and retrieves data efficiently by associating unique keys to values. It works like a digital dictionary where you can quickly find a value using its key, but keys cannot be enumerated or iterated over.
⚙️

How It Works

A mapping in Solidity is similar to a real-life dictionary or phone book where you look up a person's phone number by their name. Here, the 'name' is the key, and the 'phone number' is the value. When you provide a key, the mapping instantly gives you the associated value.

Unlike arrays, mappings do not store keys in order and you cannot list all keys stored. This is because mappings are optimized for fast access, not for iteration. Think of it as a locked filing cabinet where you can quickly open a drawer if you know the exact label, but you cannot see all labels at once.

In Solidity, mappings are declared with a syntax like mapping(KeyType => ValueType). The key type can be simple types like address or uint, and the value can be any type, including another mapping.

💻

Example

This example shows a simple contract that uses a mapping to store and retrieve balances for addresses.

solidity
pragma solidity ^0.8.0;

contract SimpleBank {
    mapping(address => uint) public balances;

    // Deposit some amount to your balance
    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }

    // Check your balance
    function getBalance() public view returns (uint) {
        return balances[msg.sender];
    }
}
🎯

When to Use

Use mappings in Solidity when you need to associate unique keys with values for fast lookup, such as tracking user balances, storing permissions, or recording votes. They are ideal when you do not need to list all keys but want quick access to data by key.

For example, in a token contract, a mapping can keep track of how many tokens each address owns. In access control, mappings can store which addresses have special roles. However, if you need to iterate over all entries, mappings alone are not suitable because Solidity does not support enumerating keys.

Key Points

  • Mapping is a key-value store optimized for fast access.
  • Keys cannot be enumerated or iterated over.
  • Keys must be of simple types like address or uint.
  • Values can be any type, including other mappings.
  • Commonly used for balances, permissions, and quick lookups.

Key Takeaways

Mapping in Solidity stores data as key-value pairs for fast access by key.
You cannot list or iterate over keys in a mapping.
Use mappings to track balances, permissions, or any data needing quick lookup.
Keys must be simple types like addresses or integers.
Mappings are not suitable when you need to enumerate all stored keys.