Mappings are a fundamental data structure in Solidity, crucial for efficient key-value pair storage in Ethereum smart contracts. They provide a hash table-like mechanism for quick data retrieval and manipulation.
In Solidity, a mapping is a key-value data structure that allows you to store and retrieve values based on unique keys. It's similar to hash tables or dictionaries in other programming languages. Mappings are particularly useful for creating associations between data in smart contracts.
The basic syntax for declaring a mapping in Solidity is:
mapping(KeyType => ValueType) public mappingName;
Where:
KeyType
can be any built-in value type, like uint
, address
, or bytes32
ValueType
can be any type, including another mapping or an arraymappingName
is the identifier for your mappingkeccak256
hashes are used to look up valuesHere's a simple example of how to use a mapping in Solidity:
pragma solidity ^0.8.0;
contract UserBalances {
mapping(address => uint) public balances;
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function getBalance(address user) public view returns (uint) {
return balances[user];
}
}
In this example, we use a mapping to associate Ethereum addresses with their balances. The deposit
function allows users to add funds, while getBalance
retrieves the balance for a given address.
Solidity also supports nested mappings, which are useful for more complex data structures:
mapping(address => mapping(uint => bool)) public userItemOwnership;
This nested mapping could be used to track whether a user (identified by their address) owns a particular item (identified by an item ID).
Mappings are a powerful feature in Solidity, enabling efficient data storage and retrieval in smart contracts. By understanding their syntax, usage, and limitations, developers can leverage mappings to create more sophisticated and gas-efficient Ethereum applications.
For more advanced topics related to Solidity data structures, explore Solidity Arrays and Solidity Structs.