
Solidity Mappings Tutorial: A Complete Guide to Storage Optimization

image
Mappings are fundamental data structures in Solidity that create relationships between two values using key-value pairs. Think of them as hash tables or dictionaries in other programming languages.
A mapping uses the syntax
mapping(KeyType => ValueType)where KeyType can be any built-in value type and ValueType can be any type including another mapping or array.
Basic example of a mapping:
mapping(address => uint) public balances;
Key characteristics of mappings:
- All possible keys exist by default and are initialized to zero-value
- You cannot get the size/length of a mapping
- Keys are not stored, only their keccak256 hashes
- Cannot iterate through mappings directly
- Extremely gas-efficient for lookups
Common use cases:
- Token balances tracking
- User permissions and roles
- Game state storage
- Relationship tracking between addresses
Example of nested mappings:
mapping(address => mapping(uint => bool)) public nestedMapping;
Best practices:
- Always validate inputs before storing
- Consider using structs for complex value types
- Be cautious with public mappings as they create automatic getter functions
- Use events to track mapping changes
- Consider mapping alternatives if iteration is needed
Mappings are perfect for direct lookups but if you need enumeration or size tracking, consider combining them with arrays or implementing a separate counting mechanism.
Remember: Values in mappings cannot be deleted in the traditional sense - they can only be reset to their default values using the delete keyword.
Related Articles
AlgoKit 3.0 Launches with TypeScript Support and Advanced Developer Tools for Algorand
