Skip to content
Home » Answers » Understand mappings in Solidity

Understand mappings in Solidity

QA Blogs Understand mappings in Solidity

Imagine you’re building a complex smart contract, a self-executing program on the blockchain. You need a way to store and manage data efficiently. That’s where mappings come in – powerful tools in Solidity that act like digital dictionaries. They allow you to associate unique keys with corresponding values, making data retrieval and manipulation a breeze.

Think of a Telephone Directory, But on the Blockchain

In the real world, you use a phone directory to find phone numbers associated with specific names. Mappings work similarly in Solidity. Here’s the breakdown:

  • Keys: These are unique identifiers that act like names in the phone directory. Keys can be of various data types like addresses, integers, or even strings.
  • Values: These are the actual pieces of information you want to store, like phone numbers in the directory analogy. Values can be any data type supported by Solidity, including numbers, strings, arrays, or even other mappings (nested mappings!).

🔥 Check this course out: Build a Semi-Fungible ERC404 Tokens’ Marketplace

Declaring and Initializing Mappings

Here’s how you declare and initialize a mapping in Solidity:

mapping(KeyType => ValueType) public myMapping;

// Example: Mapping addresses to their favorite numbers
mapping(address => uint256) public favoriteNumbers;

In this example:

  • mapping(address => uint256) defines the mapping type. It tells the compiler that the mapping associates address keys (like Ethereum addresses) with uint256 values (unsigned integers).
  • public myMapping declares a variable named myMapping of the mapping type. Setting it to public allows anyone to read the values associated with keys in this mapping.

Adding and Retrieving Data

Now that you have your mapping set up, let’s see how to add and retrieve data:

  • Adding: Use the assignment operator (=) to associate a value with a key.
favoriteNumbers[msg.sender] = 42; // Assign the value 42 to the key msg.sender (sender's address
  • Retrieving: Use the key within square brackets [] to access the value associated with that key.
uint256 storedNumber = favoriteNumbers[msg.sender]; // Get the favorite number stored at msg.sender's address

Example: Keeping Track of High Scores in a Game

Let’s look at a more practical example. Imagine you’re building a game on the blockchain where players can compete for the highest score. You can use a mapping to track each player’s address as the key and their high score as the value:

mapping(address => uint256) public highScores;

function updateHighScore(uint256 newScore) public {
  if (newScore > highScores[msg.sender]) {
    highScores[msg.sender] = newScore;

In this example:

  • The highScores mapping stores player addresses as keys and their high scores as values.
  • The updateHighScore function checks if the new score is higher than the player’s existing score stored in the mapping.
  • If the new score is higher, the mapping is updated with the new score for that player’s address.

🔥 Check this course out: Build a One Piece Personality dApp With Solidity

Key Points to Remember About Mappings

Here are some crucial aspects to remember when using mappings:

  • Uniqueness of Keys: Keys within a mapping must be unique. You can’t have two entries with the same key.
  • Default Values: Mappings don’t have a default value. Attempting to access a non-existent key will result in an error.
  • Storage vs. Memory: Mappings are stored on the blockchain, making them more expensive to access compared to memory variables. Optimize your code to minimize unnecessary mapping reads and writes.

Further Exploration: Advanced Mapping Techniques

While these basics equip you with the power of mappings, Solidity offers more advanced features:

  • Nested Mappings: You can create mappings within mappings for more complex data structures.
  • Mapping Deletion: While there’s no direct deletion function, you can overwrite a value with a zero-value of its type to effectively remove it.

By understanding these concepts, you can leverage mappings effectively in your Solidity smart contracts for various use cases, from storing user preferences to managing complex game mechanics. Happy coding!

Try it out, ask us questions, and tell us how it went by tagging Metaschool on Social Media.

Follow us on –

🔮Twitter –

🔗LinkedIn –