Mappings/Dictionaries in solidity
Mappings are a key-value data structure in Solidity that enable you to store and look up data in a more efficient way than a traditional array. Mappings are defined in the following way:
Solidity
Copy
mapping (keyType => valueType) public myMapping;
keyType can be any built-in primitive type or a user-defined contract type,
valueType can be any type, including other mappings.
public is the visibility modifier.
Different ways to create a map in solidity :
Solidity
Copy
# Mapping with uint Keys and uint Values:
mapping(uint256 => uint256) public uintToUintMap;
# Mapping with address Keys and uint Values:
mapping(address => uint256) public addressToUintMap;
# Mapping with string Keys and Custom Struct Values:
struct Person {
uint256 age;
string name;
}
mapping(string => Person) public stringToStructMap;
# Mapping with bytes32 Keys and bool Values:
mapping(bytes32 => bool) public bytesToBoolMap;
# Nested Mappings: A map inside a map
mapping(address => mapping(string => uint256)) public nestedMap;
Mappings are similar to hashes or dictionaries in other programming languages, where each key maps to a value. One key difference with mappings in Solidity is that you don't have to predefine all the keys, as you do with an array. Instead, you can add and remove keys dynamically.
Mappings are often used to store data that can be looked up by a unique identifier, such as an address or an ID. For example, you might use a mapping to store the balance of each address in a cryptocurrency contract.
One limitation of mappings is that you can't iterate over them, so you can't get a list of all the keys or values. However, you can use a separate data structure to keep track of the keys if you need to iterate over them.
Overall, mappings are a powerful tool in Solidity for storing and looking up data, and they are a fundamental part of many smart contract applications.
Things to consider while using maps in solidity :
Key collision : Maps in Solidity are not like traditional hash maps. They don't automatically handle collisions, and if you use a key that already exists, it will overwrite the existing value. Be cautious about potential key collisions and handle them appropriately in your contract logic.
Gas Costs: Writing to and reading from maps can consume gas in Ethereum smart contracts. The cost depends on the complexity and size of the data being stored. Be mindful of gas costs, especially in situations where gas efficiency is critical.
Iterating : You cannot loop through a mapping in solidity. Mapping doesn’t have a length parameter. It doesn’t have an indices at all.