Solidity provides a data structure mapping to store keys and values in a hashtable kind of format.

It is similar to hashtable in java and Map in javascript and typescript. It is a reference type similar to Array and struct. In SOlidity, It does not support the loop to map keys and values.

Syntax:

mapping(keyType=> valueType) public mappingVariable;

Notes:

  • keyType allows any value data types except string and array. reference types are not allowed such as Array, Struct, and Mapping.
  • valueType It can be any type(value or reference types)
  • For every key that exists in Solidity, the Default value is zero’s bytes in type
  • No limit on the size of mapping in solidity
  • Mapping uses storage and not Memory, Hence, state variables are used.
  • default visibility for mapping is public

How to declare a mapping in Solidity?

First, Define the variable declaration using the mapping keyword, and declare the data type of the key and value.

Created a mapping and each key store’s address type and value is Employee type. Here is an example to declare a solidity where the key is addressed and the value is Employee. The employee is a custom type declared with struct.

// Solidity program example for Mapping reference type
pragma solidity ^0.5.0;

// Defining contract
contract MappingTest {

    //Declare Employee structure
    struct Employee
    {
        uint8 id;
        string subject;
        uint8 marks;
    }

    // Creating a mapping for address and employee
    mapping (address => Employee) employees;
    address[] public employeesArray;
}

How to add values to Mapping in solidity?

This example writes a value for a given key.

Here is an example code

 function add(string memory key, string name) public returns (bool){
        employees[key].name = name;
        return true;
}