Solidity

Solidity Mappings

Solidity Mappings Main Tips

  • Mapping can be interpreted as sort of hash tables that are initialized virtually so that each potential key exists and is mapped to a value, whose byte-representation consists of zeroes only.
  • However, differently from hash tables, the key data is not stored in the mapping. Instead, only its kecak256 hash used for storing the value is.

Solidity Mappings

Mapping types have to be declared using mapping(_KeyType => _ValueType).

In this example _KeyType may be nearly any type except for a mapping, a dynamic array, an enum, a contract and a struct. _ValueType , on the other hand, can actually be any type Solidity provides, including mappings.

Because of this, mappings do not have a length or a concept of a key or value being “set”.

Mappings can be used for state variables only (or as reference types for storage in internal functions).

You can also mark mappings public and have Solidity create a getter for them. The _KeyType then becomes a required parameter for the getter and returns _ValueType.

The _ValueType may turn out tp be a mapping too. For this, the getter will have a single parameter for every _KeyType, recursively.

Example

pragma solidity ^0.4.0;

contract exampleMapping {
    mapping(address => uint) public balances;

    function update(uint balanceNew) {
        balances[msg.sender] = balanceNew;
    }
}

contract userMapping {
    function f() returns (uint) {
        exampleMapping m = new exampleMapping();
        m.update(100);
        return m.balances(this);
    }
}

 

Try on Remix Try live on Hosting

Note: You cannot iterate mappings, but implementing a data structure on top is possible. For example, you should look into iterable mapping.

Read previous post:
Solidity Reference Types

Solidity Reference Types Main Tips Complex types do not always fit into 256 bytes and have to be handled more...

Close