DEV Community

Cover image for Mapping in solidity
tawseef nabi
tawseef nabi

Posted on

3 2

Mapping in solidity

Mapping in Solidity acts like a hash table or dictionary in any other language.

mapping(key => value) <access specifier> <name>;
Enter fullscreen mode Exit fullscreen mode

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 a mapping, a dynamically sized array, a contract, an enum and a struct.
  • 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

Enter fullscreen mode Exit fullscreen mode

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
    }

}
Enter fullscreen mode Exit fullscreen mode

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
    }

}
Enter fullscreen mode Exit fullscreen mode

Common Use case
associate unique Ethereum addresses with associated unique values

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more