-
bitcoin $76624.373304 USD
-1.79% -
ethereum $2250.136487 USD
-1.36% -
tether $0.998277 USD
-0.04% -
bnb $691.737526 USD
-2.23% -
xrp $1.250415 USD
0.10% -
usd-coin $0.999636 USD
-0.01% -
solana $91.769993 USD
-2.60% -
tron $0.320718 USD
1.77% -
hyperliquid $83.540560 USD
-2.42% -
zcash $1129.534445 USD
-10.74% -
dogecoin $0.073771 USD
-2.08% -
monero $615.670132 USD
1.37% -
unus-sed-leo $9.294663 USD
-1.19% -
chainlink $11.068406 USD
-2.21% -
cardano $0.186724 USD
-2.00%
What is a mapping in Solidity and how does it store key-value pairs?
Mappings in Solidity enable efficient, gas-optimized key-value storage using keccak256 hashing, ideal for balances, access control, and lookup-heavy smart contract use cases.
Nov 10, 2025 at 12:20 pm
Understanding Mappings in Solidity
1. A mapping in Solidity is a reference type used to store data in the form of key-value pairs, similar to hash tables or dictionaries in other programming languages. It allows developers to associate a unique key with a specific value, enabling efficient lookups and updates.
2. The syntax for declaring a mapping is mapping(keyType => valueType), where keyType can be almost any elementary type such as uint, address, or bytes, but not reference types like arrays or other mappings. The valueType can be any type, including structs, arrays, or even another mapping.
3. Mappings are declared within contracts and are typically used for maintaining state variables. Because they are stored in storage, their values persist across function calls and transactions.
4. One defining characteristic of mappings is that they cannot be iterated. There is no built-in mechanism to retrieve a list of keys or values. This limitation stems from how Ethereum’s storage model works—mappings are designed for fast access by key, not enumeration.
5. When a mapping is created, all possible keys are initialized with the default value of the valueType (e.g., 0 for integers, false for booleans). This means accessing a non-existent key returns the default value rather than throwing an error.
Storage Mechanism Behind Mappings
1. Mappings do not store data in a traditional table format. Instead, Solidity uses the keccak256 hash function to compute storage slots dynamically. Each key is hashed using keccak256 along with the storage slot position of the mapping variable.
2. For a state variable mapping located at storage slot n, the value associated with a given key is stored at keccak256(key . slot), where '.' denotes concatenation. This ensures each key maps to a unique, deterministic location in storage.
3. Because the hash function is one-way, it's computationally infeasible to reverse-engineer which keys have been set. This contributes to the inability to iterate over mappings.
4. Nested mappings follow the same principle. In a mapping like mapping(address => mapping(uint => bool)), the inner mapping's slot is determined by hashing the outer key and the outer mapping's slot, then using that result as the base for the inner key lookup.
5. This hashing-based storage layout makes mappings highly efficient for read and write operations, both of which execute in constant time, regardless of the number of entries.
Practical Use Cases in Smart Contracts
1. One common use of mappings is tracking user balances in ERC-20 tokens. A mapping like mapping(address => uint256) private _balances allows quick retrieval and update of token holdings for any wallet address.
2. Access control systems often employ mappings to identify roles or permissions. For example, mapping(address => bool) public isAdmin can efficiently verify whether an address has administrative privileges.
3. In decentralized exchanges or NFT marketplaces, mappings link order IDs or token IDs to structured data such as price, owner, or listing status. This enables instant lookup of trade details without scanning large datasets.
4. Mappings are also used to prevent reentrancy attacks by marking addresses during function execution. A simple mapping(address => bool) private entered can act as a lock mechanism.
5. Due to their gas-efficient access patterns, mappings are preferred over arrays when frequent lookups by identifier are required, especially in high-throughput protocols.
Frequently Asked Questions
Can mappings be deleted entirely?Yes, using the delete keyword on a mapping clears all entries by resetting each written slot to its default value. However, because mappings are virtually initialized with default values for all keys, this operation only affects keys that were explicitly assigned.
Is it possible to return a mapping from a function?No, mappings cannot be returned directly from functions because they are not valid return types in Solidity. Only specific values accessed via a key can be returned.
Can string or dynamic arrays be used as mapping keys?String and dynamic byte arrays cannot be used as mapping keys. Only fixed-size data types such as bytes32, uint, and address are allowed. Strings must be converted to a fixed-size format like bytes32 if needed.
How do mappings affect gas costs?Reading from a mapping with an uninitialized key consumes less gas since it returns the default value without modifying storage. Writing or updating a value incurs higher gas, especially if it changes a zero value to non-zero, due to Ethereum’s state growth cost rules.
Disclaimer:info@kdj.com
The information provided is not trading advice. kdj.com does not assume any responsibility for any investments made based on the information provided in this article. Cryptocurrencies are highly volatile and it is highly recommended that you invest with caution after thorough research!
If you believe that the content used on this website infringes your copyright, please contact us immediately (info@kdj.com) and we will delete it promptly.
- US Midterms, Prediction Markets & Crypto Races: A High-Stakes Wager on Washington's Future
- 2026-11-04 04:30:22
- Digital Assets, Global Finance, and AI: Navigating the Next Frontier at DavosWeb3 and Beyond
- 2026-11-04 04:30:22
- Avalanche AVAX Price Dips Amid Broader Market Woes; Institutional Interest Remains Strong
- 2026-11-03 12:35:02
- Why Is Quant Price Down? A Deep Dive into QNT's Recent Slide Amidst Market Jitters
- 2026-11-03 12:55:01
- Egrag Crypto's XRP Price Chart Analysis: Are You Ready for the 'Biggest Wave 3'?
- 2026-11-03 01:15:01
- Bed Bath & Beyond's Parent Company Backs tZERO's $350 Million Valuation SPAC Deal: What New Yorkers Need to Know
- 2026-11-03 01:15:01
Related knowledge
How to Calculate the Total Cost of Holding a BTCUSDT Futures Position
Oct 26,2026 at 04:06am
Total Cost Components for BTCUSDT Futures Positions1. The total cost of holding a BTCUSDT futures position includes both explicit and implicit charges...
How to Monitor XRPUSDT Funding Rates and Open Interest Together
Oct 20,2026 at 06:39pm
Funding Rate Mechanics on XRPUSDT Perpetual Contracts1. Funding rates on XRPUSDT perpetual swaps are calculated every eight hours using the premium in...
How to Set a Break-Even Stop-Loss on SOLUSDT Perpetual Futures
Oct 23,2026 at 09:34am
Understanding Break-Even Stop-Loss Mechanics1. A break-even stop-loss is a dynamic order that adjusts upward as the position moves profitably, locking...
How to Use the Binance Futures Calculator for ETHUSDT Trades
Oct 21,2026 at 02:00am
Understanding the Binance Futures Calculator Interface1. The calculator is embedded directly within the Binance Futures trading interface, accessible ...
How to Check BTCUSDT Mark Price Before a Futures Liquidation
Oct 26,2026 at 12:20pm
Understanding Mark Price in BTCUSDT Futures1. The mark price is a calculated value used by exchanges to prevent unfair liquidations during volatile ma...
How to Adjust Leverage on a TRUMPUSDT Perpetual Contract
Oct 30,2026 at 10:19pm
Understanding TRUMPUSDT Perpetual Contract Mechanics1. TRUMPUSDT is a thematic perpetual futures contract listed on multiple Tier-1 derivatives exchan...
How to Calculate the Total Cost of Holding a BTCUSDT Futures Position
Oct 26,2026 at 04:06am
Total Cost Components for BTCUSDT Futures Positions1. The total cost of holding a BTCUSDT futures position includes both explicit and implicit charges...
How to Monitor XRPUSDT Funding Rates and Open Interest Together
Oct 20,2026 at 06:39pm
Funding Rate Mechanics on XRPUSDT Perpetual Contracts1. Funding rates on XRPUSDT perpetual swaps are calculated every eight hours using the premium in...
How to Set a Break-Even Stop-Loss on SOLUSDT Perpetual Futures
Oct 23,2026 at 09:34am
Understanding Break-Even Stop-Loss Mechanics1. A break-even stop-loss is a dynamic order that adjusts upward as the position moves profitably, locking...
How to Use the Binance Futures Calculator for ETHUSDT Trades
Oct 21,2026 at 02:00am
Understanding the Binance Futures Calculator Interface1. The calculator is embedded directly within the Binance Futures trading interface, accessible ...
How to Check BTCUSDT Mark Price Before a Futures Liquidation
Oct 26,2026 at 12:20pm
Understanding Mark Price in BTCUSDT Futures1. The mark price is a calculated value used by exchanges to prevent unfair liquidations during volatile ma...
How to Adjust Leverage on a TRUMPUSDT Perpetual Contract
Oct 30,2026 at 10:19pm
Understanding TRUMPUSDT Perpetual Contract Mechanics1. TRUMPUSDT is a thematic perpetual futures contract listed on multiple Tier-1 derivatives exchan...
See all articles














