Mapping
Last updated
Last updated
In Solidity, a mapping
is a type of data structure that maps unique keys to values. It is similar to a hash table or a dictionary in other programming languages. The mapping
type is defined using the following syntax:
where keyType
is the data type of the key, valueType
is the data type of the value, and mappingName
is the name of the mapping.
Here is an example of a mapping
that maps addresses to integers:
In this example, address
is the key type, uint
(unsigned integer) is the value type, and balances
is the name of the mapping. Each address in the mapping will have a corresponding uint value representing their balance.
You can add values to the mapping using the following syntax:
For example:
This sets the balance for the msg.sender
address to 100.
You can also retrieve values from the mapping using the following syntax:
For example:
This retrieves the balance for the msg.sender
address and stores it in the myBalance
variable.
mapping
is a powerful data structure in Solidity and is commonly used to store and retrieve data in smart contracts.
In Solidity, it is possible to have nested mappings, where the value of an outer mapping is another mapping. This allows you to create more complex data structures that can be useful in some cases.
Here is an example of a nested mapping that maps addresses to a mapping of strings to integers:
In this example, address
is the key type for the outer mapping, string
is the key type for the inner mapping, and uint
is the value type for the inner mapping. The userInfo
mapping maps each address to another mapping that contains user-specific information.
You can add values to the nested mapping using the following syntax:
For example:
This sets the age for the msg.sender
address to 30.
You can retrieve values from the nested mapping using the following syntax:
For example:
This retrieves the age for the msg.sender
address and stores it in the myAge
variable.
Nested mappings can be useful when you need to store complex data structures in your smart contracts. However, it is important to be mindful of gas costs and potential storage limitations, as nested mappings can be more expensive to use and can consume more storage space.
In this example, we have two addresses (0x123
and 0x456
) mapped to another mapping of user information. The user information mapping contains two key-value pairs for each address: "age"
and "height"
, with their corresponding values.
To retrieve the age for 0x123
, we would use the following syntax:
This would set the age
variable to 30
.
To update the height for 0x456
, we would use the following syntax:
This would update the height for 0x456
to 170
.
Nested mappings can be useful when you need to store more complex data structures in your smart contracts, such as user profiles or account balances for different tokens. They allow you to efficiently store and retrieve data in a structured way.