solidity logo

Question: What is the mapping Data Structure in Solidity? Provide an Example of How to Use Mapping to Store and Retrieve Data.

In Solidity, the mapping data structure functions like a hash table. It is a collection of key-value pairs, where the key serves as the index and the value is the associated data. Mappings can be arbitrarily large, and their size does not need to be known at compile time.

Key Characteristics of mapping

  • Keys: Can be most built-in types such as bool, int, uint, or address. However, mappings, arrays, or contracts cannot be used as keys.
  • Values: Can be of any type, including complex types such as structs or even other mappings.
  • Default Values: When a mapping is created, all values are initialized to their default. For integers, this default is 0.
  • Storage Only: Mappings exist only in storage, not in memory.

Example: Storing and Retrieving User Data

The following example demonstrates how to declare a mapping in a smart contract and use it to store and retrieve user information:

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

contract UserInfo {
    // Declare a mapping that maps an address to a uint, representing user scores
    mapping(address => uint) public userScores;

    // Function to add or update a user’s score
    function addScore(address _user, uint _score) public {
        userScores[_user] = _score;
    }

    // Function to retrieve a user’s score
    function getScore(address _user) public view returns (uint) {
        return userScores[_user];
    }
}

Explanation

In this example, we define a UserInfo contract containing a mapping userScores, which maps a user’s address (address) to their score (uint).

  • The addScore function is used to add or update a score for a specific user.
  • The getScore function retrieves the score of a user.
  • If a user has not been assigned a score, the mapping returns the default value of 0.

Why Use Mapping?

One of the most important features of mappings is that they allow O(1) lookup time, which means that no matter how many entries are stored, retrieving a value is always efficient.

This makes mapping an extremely powerful and commonly used data structure in Solidity, especially for use cases that require fast and efficient data retrieval, such as user balances, voting records, or transaction confirmations.

Subscribe for New Articles!

Leave a Comment

Your email address will not be published. Required fields are marked *