What is Solidity mapping?

Overview

Mapping is identical to a dictionary in every other language. In Solidity, it’s a hash table that stores data as key-value pairs, with the key being any of the built-in data types but not reference types, and the value being any type. When it comes to Solidity and the Ethereum blockchain, mappings are most commonly used to link a unique Ethereum address to a corresponding value type.

What is mapping?

Any other variable type that accepts a key type and a value type is referred to as mapping.

Syntax

mapping(key => value) <access specifier> <name>;

Creating mapping

Example

A structure is defined and a mapping is made in the contract mapping example.

pragma solidity ^0.5.12;
// Defining contract
contract mapping_sample {
//Defining structure
struct worker
{
string worker;
string duty;
uint8 renumeration;
}
// Creating a mapping
mapping (address => worker) result;
address[] public worker_result;
}

Code explanation

  • In line 4, we define a contract.

  • In lines 7-12, we define the structure for the worker.

  • In line 15, we declare the different structure elements regarding the worker.

  • In line 16, we create the mapping.