Concept Flow - Mappings
Start
Define mapping
Add key-value pair
Access value by key
Update or delete value
End
This flow shows how a mapping is defined, used to store key-value pairs, accessed, updated, and deleted in blockchain smart contracts.
mapping(address => uint) balances;
function updateBalance(address user, uint amount) public {
balances[user] = amount;
}
function getBalance(address user) public view returns (uint) {
return balances[user];
}
function deleteBalance(address user) public {
delete balances[user];
}| Step | Action | Key (address) | Value (uint) | Mapping State | Output |
|---|---|---|---|---|---|
| 1 | Define empty mapping | - | - | {} | - |
| 2 | Call updateBalance(user1, 100) | user1 | 100 | {user1: 100} | - |
| 3 | Call updateBalance(user2, 50) | user2 | 50 | {user1: 100, user2: 50} | - |
| 4 | Call getBalance(user1) | user1 | - | {user1: 100, user2: 50} | 100 |
| 5 | Call updateBalance(user1, 200) | user1 | 200 | {user1: 200, user2: 50} | - |
| 6 | Call getBalance(user1) | user1 | - | {user1: 200, user2: 50} | 200 |
| 7 | Call getBalance(user3) (not set) | user3 | - | {user1: 200, user2: 50} | 0 |
| 8 | Delete balances[user2] | user2 | - | {user1: 200} | - |
| 9 | Call getBalance(user2) | user2 | - | {user1: 200} | 0 |
| Variable | Start | After Step 2 | After Step 3 | After Step 5 | After Step 8 | Final |
|---|---|---|---|---|---|---|
| balances | {} | {user1: 100} | {user1: 100, user2: 50} | {user1: 200, user2: 50} | {user1: 200} | {user1: 200} |
Mappings store key-value pairs like a dictionary. Keys map to values; if key missing, returns default value. Use mapping(keyType => valueType) syntax. Update by assigning new value to a key. Delete keys to reset to default. Common in blockchain for balances and states.