65 - Mapping Types
Mappings define key-value pairs and are declared using the syntax mapping(KeyType => ValueType) VariableName.
-
The KeyType can be any built-in value type,
bytes
,string
, or anycontract
orenum
type. Other user-defined or complex types, such asmappings
,structs
orarray
types are not allowed. ValueType can be any type, includingmappings
,arrays
andstructs
. -
Key data is not stored in a mapping, only its keccak256 hash is used to look up the value
-
They do not have a length or a concept of a key or value being set
-
They can only have a data location of storage and thus are allowed for state variables, as storage reference types in functions, or as parameters for library functions
-
They cannot be used as parameters or return parameters of contract functions that are publicly visible. These restrictions are also true for arrays and structs that contain mappings.
-
You cannot iterate over mappings, i.e. you cannot enumerate their keys. It is possible, though, to implement a data structure on top of them and iterate over that.
- Key-Value Pairs
mapping(KeyType => ValueType) VariableName.
- Key Type -> Restricted
- Value Type -> Any
- Key Value -> Not Stored
- Keccak256 Lookup
- No Length/Set, Storage Only, No Iteration
```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
contract Mapping {
// Mapping from address to uint
mapping(address => uint) public myMap;
function get(address _addr) public view returns (uint) {
// Mapping always returns a value.
// If the value was never set, it will return the default value.
return myMap[_addr];
}
function set(address _addr, uint _i) public {
// Update the value at this address
myMap[_addr] = _i;
}
function remove(address _addr) public {
// Reset the value to the default value.
delete myMap[_addr];
}
}
contract NestedMapping {
// Nested mapping (mapping from address to another mapping)
mapping(address => mapping(uint => bool)) public nested;
function get(address _addr1, uint _i) public view returns (bool) {
// You can get values from a nested mapping
// even when it is not initialized
return nested[_addr1][_i];
}
function set(
address _addr1,
uint _i,
bool _boo
) public {
nested[_addr1][_i] = _boo;
}
function remove(address _addr1, uint _i) public {
delete nested[_addr1][_i];
}
}