A mapping in Solidity is a reference type that acts like a hash table or dictionary, allowing you to associate a unique key with a value. Mappings are used to store data in a key-value format, making it easy to look up values based on their corresponding keys. They are a powerful tool for managing state in smart contracts.

Key Features of Mappings

  • Key-Value Pair: Mappings store data in pairs, where each key maps to a specific value.
  • Dynamic Size: Mappings do not have a fixed size; they can grow dynamically as new keys are added.
  • No Enumeration: You cannot iterate over the keys or values in a mapping. To retrieve values, you need to know the keys.
  • Default Values: If a key does not exist in the mapping, it returns the default value for the value type (e.g., 0 for integers, false for booleans).

Declaring a Mapping

To declare a mapping, use the following syntax:

mapping(<keyType> => <valueType>) public mappingName;

Here, <keyType> is the data type of the key, and <valueType> is the data type of the value.

Sample Code for Mappings


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

contract SimpleStorage {
// Declare a mapping from address to uint256
mapping(address => uint256) public balances;

// Function to set the balance for a specific address
function setBalance(uint256 amount) public {
balances[msg.sender] = amount; // Set the balance for the sender's address
}

// Function to get the balance for a specific address
function getBalance(address account) public view returns (uint256) {
return balances[account]; // Return the balance for the specified address
}
}

Explanation of the Sample Code

In the example above:

  • The contract SimpleStorage defines a mapping called balances that maps an address to a uint256 value.
  • The setBalance function allows users to set their balance by providing an amount. The function uses msg.sender to identify the address of the caller and assigns the specified amount to that address in the mapping.
  • The <keyType>0 function retrieves the balance for a specified address and returns it.

Mappings with Structs

Mappings can also be used with structs to create more complex data structures. Here’s an example:

<keyType>1

Conclusion

Mappings in Solidity are a fundamental data structure that allows developers to store and manage key-value pairs efficiently. They are particularly useful for scenarios where quick lookups are necessary, such as tracking balances or user information. By leveraging mappings, developers can create more organized and efficient smart contracts.