0
0
Blockchain / Solidityprogramming~3 mins

Why Mappings in Blockchain / Solidity? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could instantly find any user's balance without searching through a long list every time?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
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;
}
After
mapping(address => uint) balances;

function getBalance(address user) public view returns (uint) {
  return balances[user];
}
What It Enables

Mappings enable fast, direct access to data by key, making blockchain contracts more efficient and secure.

Real Life Example

In a cryptocurrency wallet contract, mappings let you quickly find how many tokens each user owns without searching through all users.

Key Takeaways

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.