Mapping in Solidity

Mapping in Solidity
- 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;
where
keyTypeis the data type of the keys,valueTypeis the data type of the values, andmappingNameis the name you give to the mapping.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;
This creates a mapping called
ageMapthat maps a string (the name of the person) to a uint (their age).To add or update a value in the mapping, you can simply use the square bracket notation with the key:
ageMap["Alice"] = 25;
- 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"];
This retrieves the value for the key "Alice" and assigns it to the variable
aliceAge.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
containsfunction provided by the Solidity Collections library.




