Mapping in solidity
tawseef nabi
Posted on January 22, 2022
Mapping in Solidity acts like a hash table or dictionary in any other language.
mapping(key => value) <access specifier> <name>;
keys are mapped to a value. Data isn't stored in a mapping, only its hash value.
- key: any built-in types like
uint
,bytes
,string
except for amapping
,a dynamically sized array
, acontract
, anenum
and astruct
. - value: any type including
mapping
,struct
,arrays
They don't have a length and you can't iterate through the mapping.
e.g.
// mapping declaration
mapping(uint => string )public people
// update mapping
people[10] = 'Mark'; // assigns a value
people[12] = 'Andrew';
// reading values
people[1] // reads a value
people[unknown_key] //will return the default value of the type, i.e '' for string or 0 for unint
Assign an array as a map value
We can assign an array as a value type to a map and can access them as we would an array like below:
contract Mapping {
mapping(address => uint[]) scores;
function manipulateArrayMap() external {
scores[msg.sender].push(1); //assign a value;
scores[msg.sender].push(2); //assign another element
scores[msg.sender][0]; //access the element in the map array
scores[msg.sender][1] = 5; //update an element in the map array in index 1
delete scores[msg.sender][0]; //delete the element in the index 0 of the map array
}
}
Assign another map as a map value
We can also assign another map as a map value and can access them as we would access a map like below:
contract Mapping {
mapping(address => uint) balances;
mapping(address => mapping(address => bool)) approved;
function manipulateMapOfMap(spender) external {
approved[msg.sender][spender] = true //assign a value to the approved map
approved[msg.sender][spender]; //get the value of the map
delete approved[msg.sender][spender] //delete the reference
}
}
Common Use case
associate unique Ethereum addresses with associated unique values
💖 💪 🙅 🚩
tawseef nabi
Posted on January 22, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.