What if you could instantly find any user's balance without searching through a long list every time?
Why Mappings in Blockchain / Solidity? - Purpose & Use Cases
Imagine you are managing a list of users and their balances on a blockchain without any direct way to link a user to their balance. You have to search through a long list every time you want to find or update a user's balance.
This manual search is slow and costly because every lookup requires scanning through all entries. It also increases the chance of mistakes, like updating the wrong user's balance or missing a user entirely.
Mappings provide a simple and efficient way to connect a unique key, like a user address, directly to a value, like their balance. This makes lookups and updates instant and reliable.
struct User { address addr; uint balance; }
User[] users;
function getBalance(address user) public view returns (uint) {
for (uint i = 0; i < users.length; i++) {
if (users[i].addr == user) return users[i].balance;
}
return 0;
}mapping(address => uint) balances;
function getBalance(address user) public view returns (uint) {
return balances[user];
}Mappings enable fast, direct access to data by key, making blockchain contracts more efficient and secure.
In a cryptocurrency wallet contract, mappings let you quickly find how many tokens each user owns without searching through all users.
Manual searching through lists is slow and error-prone.
Mappings link keys directly to values for instant access.
This makes blockchain contracts faster and safer.