In this article, we’ll take a closer look and examine Solidity mappings and explore how they can be used in practical applications with examples.
The syntax for declaring a mapping type is as follows:
mapping(_KeyType => _ValueType)
A _KeyType can be a built-in type, a byte, or a string.
The use of complex objects or reference types is not permitted.
Any type of value can be assigned to _ValueType.
Mappings are generally used for state variables and can only have one type of storage.
You can mark solidity mapping as public. A getter is automatically created for it.
The following example shows the working of solidity mapping.
Let’s understand this by considering a mapping of car_name that could be accessed by using the id number as shown in the table below:
|Car Id||Car Name|
If we create the mapping of the car_names and id, then by accessing the respective id of the car we will get the name of the car.
Make sure that this could only be done if you set the id of the car first.
To understand the working follow the code below:
Let us now consider another data of US political parties having a political_party_name and political_party_head_name:
|American Independent||Markham Robinson|
|National States’ Rights Party||Edward Reed Fields J. B. Stoner|
The example below shows the working of mapping in a more easier way.
Here we assigned political_party_name as a _keyvalue and political_party_head_name as _value.
The working of such type of mapping is given below:
Solidity mappings are the powerful data structure that allows you to efficiently store and retrieve key-value pairs.
Mappings are widely used in smart contract development for a variety of purposes, including maintaining balances, tracking ownership, and storing data in a decentralized manner.