Mappings let you store and look up data quickly using a key, like a phone book for your smart contract.
0
0
Mappings in Blockchain / Solidity
Introduction
When you want to keep track of balances for each user address.
When you need to store settings or preferences linked to specific users.
When you want to check if an address has permission to do something.
When you want to link unique IDs to data without looping through arrays.
Syntax
Blockchain / Solidity
mapping(keyType => valueType) public myMapping;
keyType can be any built-in value type like address or uint.
valueType can be any type, including structs or other mappings.
Examples
This creates a mapping from user addresses to their token balances.
Blockchain / Solidity
mapping(address => uint) public balances;
This maps a unique ID number to the owner's address.
Blockchain / Solidity
mapping(uint => address) public idToOwner;
This is a nested mapping to track if an address approved a specific item ID.
Blockchain / Solidity
mapping(address => mapping(uint => bool)) public approvals;Sample Program
This contract lets users set their own balance and anyone can check any user's balance using their address.
Blockchain / Solidity
pragma solidity ^0.8.0; contract SimpleMapping { mapping(address => uint) public balances; function setBalance(uint _balance) public { balances[msg.sender] = _balance; } function getBalance(address _user) public view returns (uint) { return balances[_user]; } }
OutputSuccess
Important Notes
Mappings do not store keys, only values. You cannot get a list of keys from a mapping.
All keys in a mapping exist by default with a value of zero or empty until set.
Mappings are very efficient for lookups but not iterable like arrays.
Summary
Mappings store data as key-value pairs for fast access.
Keys can be simple types like addresses or numbers.
They are useful for tracking balances, ownership, and permissions in smart contracts.