Follow these steps to create mappings in solidity:
- Mappings are created with key-value pairs. A mapping can be compared with a hash table or dictionary. The following example creates a mapping of an address and a user-defined type, and another mapping with an address and an unsigned integer. These are used for storing employee data:
contract test {
struct Person {
uint id;
string name;
}
mapping(address => Person) employees;
mapping(address => uint) balances;
function insert(address _employee, uint _id,
string _name, uint _balance) public {
employees[_employee] = Person({
id: _id,
name: _name
});
balances[_employee] = _balance;
}
}
-
Mappings can be nested to create a more complex data structure:
contract test {
mapping(address => mapping(uint => bytes32)) dataStore;
function insert(uint _id, bytes32 _value) public {
dataStore[msg.sender][_id] = _value;
}
}
-
In a mapping, the key can be anything except a mapping, a dynamically sized array, a contract, an enum, or a struct. The value can be of any type.
-
The key data is not actually stored in the mapping, as only its keccak256 hash is used to look up the value. Because of this, mappings do not have a length associated with them.
-
Mappings are not iterable, but we can design a data structure to allow such operations.
Declaring an array or mapping as a public variable generates a getter method for it. In a mapping, the key will become a parameter for the getter and it will return the value. For an array, the index will become the parameter.