In Solidity when you want to store a collection of data you can use array or mapping. In this article, I will show you how to create a mapping and how to add keys and values using the constructor function.
Following the Solidity documentation “You can think of mappings as hash tables, which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros, a type’s default value”
In other words, mapping in Solidity is like a dictionary in Python or a map in JavaScript. Python allows you to iterate through a dictionary and JavaScript allows you to iterate through the map. However, in Solidity, you cannot iterate through the mapping.
Mapping use the following syntax
mapping(_KeyType => _ValueType) public mappingName
You can also use nested mapping in the following way
mapping(_KeyType => mapping(_KeyType => _ValueType)) public mappingName;
Let me explain how mapping works. The table below presents the room numbers with corresponding hotel guest names. You can think about this table as a key-value pair relationship where you can find a unique set of “keys” that correspond to a unique value.
So if you ask for the value for “102” you will receive “Sara”.
Let’s see how to create a mapping:
pragma solidity ^0.8.4;
contract MyContract {
mapping(uint => string) public names;
}
First, you need to declare mapping with the
mapping
keyword, and then specify the data type for the key and the value. In this case, each key in the mapping will be a uint
, and each corresponding value will be a string
.Before we deploy our smart contract to see how mapping works we add some data. To do that I will use the
contructor
function.constructor() public {
names[101] = "Jon";
names[102] = "Sara";
names[103] = "Paul";
}
}
Now we can deploy our simple smart contract in Remix to see how it works. Let’s click on “Deploy”.
Once the contract is deployed you can see mapping in action. To do that you need to provide a key and click on “call”.
In my example, I asked for value for key “101” and received “Jon”.
I hope this short tutorial helps you to understand the basics of mapping in Solidity.
References:
https://docs.soliditylang.org/en/v0.8.4/types.html#mapping-types