Solidity Mapping

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.

A mapping is a reference type, similar to arrays and structures.

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 IdCar 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:


// SPDX-License-Identifier: GPL-3.0pragma solidity ^0.8.0; contract SolidityTest{mapping(uint => string) public car_names;constructor() public {car_names[1]="Porsche"; car_names[2]="Ferrari"; car_names[3]="Bentley"; car_names[4]="Lamborghini"; car_names[5]="Tesla";} }
<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>

Let us now consider another data of US political parties having a political_party_name and political_party_head_name:

DemocraticJoe Biden
RepublicanRonna McDaniel
LibertarianAngela McArdle
American IndependentMarkham Robinson
National States’ Rights PartyEdward 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:


// SPDX-License-Identifier: GPL-3.0pragma solidity ^0.8.0; contract SolidityTest{mapping (uint => string) public voting_party;function set_Value() public {voting_party[1]="Democratic"; voting_party[2]="Republican"; voting_party[3]="Libertarian"; voting_party[4]="American Independent"; voting_party[5]="States' Rights";}}
<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>


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.

We value your feedback.

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!

Leave a Reply

Your email address will not be published. Required fields are marked *