Skip to main content

Command Palette

Search for a command to run...

Mapping in Solidity

Published
2 min readView as Markdown
Mapping in Solidity

Mapping in Solidity

  1. In Solidity, mapping is a data structure that allows you to store key-value pairs, similar to a dictionary or a hash table in other programming languages. The syntax for declaring a mapping is as follows:
mapping(keyType => valueType) mappingName;
  1. where keyType is the data type of the keys, valueType is the data type of the values, and mappingName is the name you give to the mapping.

  2. For example, let's say you want to create a mapping to store the age of a person based on their name. You can declare the mapping like this:

mapping(string => uint) ageMap;
  1. This creates a mapping called ageMap that maps a string (the name of the person) to a uint (their age).

  2. To add or update a value in the mapping, you can simply use the square bracket notation with the key:

ageMap["Alice"] = 25;
  1. This sets the value for the key "Alice" to 25. If you want to retrieve a value from the mapping, you can also use the square bracket notation:
uint aliceAge = ageMap["Alice"];
  1. This retrieves the value for the key "Alice" and assigns it to the variable aliceAge.

  2. Note that if you try to retrieve a value for a key that does not exist in the mapping, Solidity will return the default value for the value type (e.g., 0 for uint). To check if a key exists in the mapping, you can use the contains function provided by the Solidity Collections library.

More from this blog