Mappings
A mapping is a hash table from keys to values: mapping(address => uint256) balances;. It is the single most used data structure in Solidity: token balances, allowances, votes and roles are all mappings.
mapping(KeyType => ValueType) visibility name;
mapping(address user => uint256 amount) public deposits; // key/value names are optional (0.8.18+)- Keys can be any value type, plus
stringandbytes(structs, arrays and mappings can't be keys). - Values can be any type, including other mappings, arrays and structs.
Every key exists
A mapping behaves as if every possible key is already there with the zero value. Reading a key you never wrote returns 0, false or address(0). There's no "key not found" error.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Main {
mapping(address => uint256) public balances;
mapping(string => bool) public reservedNames;
function main() external {
address alice = address(0xA11CE);
address bob = address(0xB0B);
balances[alice] = 50;
balances[alice] += 25;
reservedNames["admin"] = true;
console.log("alice:", balances[alice]);
console.log("bob (never set):", balances[bob]);
console.log("'admin' reserved?", reservedNames["admin"]);
console.log("'guest' reserved?", reservedNames["guest"]);
delete balances[alice];
console.log("alice after delete:", balances[alice]);
}
}alice: 75
bob (never set): 0
'admin' reserved? true
'guest' reserved? false
alice after delete: 0
If you need to tell "set to zero" from "never set", store an extra flag, e.g. mapping(address => bool) registered, or use a struct with an exists field.
Mappings cannot be iterated
Keys are not stored, only the hashed location of each value. So you cannot loop over a mapping or ask for its length. If you need that, keep a separate array of keys alongside it:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Registry {
mapping(address => uint256) public points;
mapping(address => bool) public isMember;
address[] public members;
function addPoints(address who, uint256 amount) external {
if (!isMember[who]) {
isMember[who] = true;
members.push(who); // remember the key
}
points[who] += amount;
}
function memberCount() external view returns (uint256) {
return members.length;
}
function total() external view returns (uint256 sum) {
for (uint256 i = 0; i < members.length; i++) {
sum += points[members[i]];
}
}
}
contract Main {
function main() external {
Registry r = new Registry();
r.addPoints(address(0x1), 10);
r.addPoints(address(0x2), 5);
r.addPoints(address(0x1), 7);
console.log("members:", r.memberCount());
console.log("total points:", r.total());
console.log("points of 0x1:", r.points(address(0x1)));
}
}members: 2
total points: 22
points of 0x1: 17
Nested mappings
A mapping of mappings models two-key relations. The ERC-20 allowance table is the textbook example: allowance[owner][spender] is how much spender may move on behalf of owner.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Main {
mapping(address owner => mapping(address spender => uint256)) public allowance;
function main() external {
address alice = address(0xA11CE);
address shop = address(0x5408);
address bank = address(0xBA4C);
allowance[alice][shop] = 300;
allowance[alice][bank] = 1000;
console.log("alice -> shop:", allowance[alice][shop]);
console.log("alice -> bank:", allowance[alice][bank]);
console.log("shop -> alice:", allowance[shop][alice]);
}
}alice -> shop: 300
alice -> bank: 1000
shop -> alice: 0
The public getter of a nested mapping takes one argument per key: allowance(alice, shop).
Where mappings can live
Mappings can only exist in storage: as state variables, inside storage structs, or as storage references in functions. You can't create a mapping in memory, pass it to an external function, or return it. And delete on a struct or array does not clear mappings inside it, because the compiler doesn't know which keys were used.
Mapping to a struct
Combining mappings with structs gives you a small database table indexed by key:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Main {
struct Book { string title; uint16 year; bool available; }
mapping(uint256 isbn => Book) public catalog;
function main() external {
catalog[9780131103627] = Book("The C Programming Language", 1988, true);
Book storage b = catalog[9780131103627];
b.available = false; // lend it out
(string memory title, uint16 year, bool available) = this.catalog(9780131103627);
console.log(title, year, available);
console.log("unknown isbn title length:", bytes(catalog[1].title).length);
}
}The C Programming Language 1988 false
unknown isbn title length: 0
this.catalog(isbn) calls the contract's own public getter as an external call, which returns the struct's fields as a tuple. Inside the contract you would normally just read catalog[isbn].title directly; the getter is shown because that is exactly what a front end or another contract sees. A key that was never written gives a struct full of zero values, here an empty title.
Test yourself
What does balances[someAddress] return for an address that was never written?
- It reverts
0null- A random value
How do you get the number of entries in a mapping?
m.lengthm.size()- You can't; track keys or a counter yourself
keys(m).length
Which of these can be a mapping key?
- A struct
uint256[]address- Another mapping