🎓 A1Learner
🔍
0 of 50 lessons completed

Solidity Mappings

A mapping is a lookup that stores one value for each key. This lesson uses a score book that stores one score for each address.

Write a value under a key

A mapping from address to uint256 is a score book. The address is the key, and the number is the score.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract ScoreBook {
    mapping(address => uint256) public scores;

    function setScore(address player, uint256 score) public {
        scores[player] = score;
    }
}

Read a value back by its key

Give the key to read its value back. A view function can return the stored score.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract ScoreBook {
    mapping(address => uint256) public scores;

    function setScore(address player, uint256 score) public {
        scores[player] = score;
    }

    function getScore(address player) public view returns (uint256) {
        return scores[player];
    }
}

A key never written reads 0

No value was stored under this key. The mapping gives back the default value, 0.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract ScoreBook {
    mapping(address => uint256) public scores;

    function setScore(address player, uint256 score) public {
        scores[player] = score;
    }
}

Keys are independent

Each key holds its own value. Writing under one key does not change another key.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract ScoreBook {
    mapping(address => uint256) public scores;

    function setScore(address player, uint256 score) public {
        scores[player] = score;
    }
}

Example

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract ScoreBook {
    mapping(address => uint256) public scores;

    function setScore(address player, uint256 score) public {
        scores[player] = score;
    }

    function getScore(address player) public view returns (uint256) {
        return scores[player];
    }
}

Key points

  • Key: the value you look up by, such as an address.
  • Address: an account's 20-byte identifier, written like address(0xA11CE) in code.
  • Value: the data stored under a key, such as a score number.
  • Write: scores[player] = 80 stores 80 under that player's key.
  • Read: scores[player] gives back the value stored under that key.
  • Default: a key that was never written reads 0.

In this example, the ScoreBook mapping stores one score for each address. The setScore function writes a score under a player's address. The getScore function reads the score for one address back. Two players keep separate scores, and an address with no score written reads 0.

Note

a mapping has no length and cannot be looped over.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Remix IDE

Exercise

Which statement about a mapping is true?