Mappings, Structs & Nested Storage
Group related data with structs and look it up by key with mappings.
Code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Registry {
struct User {
address wallet;
uint256 balance;
bool active;
string displayName;
}
// mapping: key -> value (no iteration, no length)
mapping(address => User) public users;
mapping(address => mapping(uint256 => bool)) public approvals; // nested
address[] public userIndex; // for iteration
function register(string calldata name) external {
require(!users[msg.sender].active, "already registered");
users[msg.sender] = User({
wallet: msg.sender,
balance: 0,
active: true,
displayName: name
});
userIndex.push(msg.sender);
}
function approve(uint256 id) external {
approvals[msg.sender][id] = true;
}
function count() external view returns (uint256) {
return userIndex.length;
}
}Explanation
Mappings are hash tables: keccak256(key) points to a storage slot, so lookup is O(1) but you can't iterate keys or get length — keep a separate array as an index when you need enumeration. Structs group fields; you can assign with named or positional syntax. Nested mappings (mapping(A => mapping(B => C))) are common for ACLs. Storage structs containing mappings or dynamic types live in their own slots; copying a storage struct to memory drops nested mappings (they don't fit in memory).
More Solidity Snippets
Contract Basics
Define a basic smart contract with state and functions.
Functions and Visibility
Function visibility, payable, and return values.
Modifiers and Access Control
Reuse validation logic with modifiers.
Events and Logs
Emit events for off-chain listeners.
Inheritance, Abstract & Interfaces
Reuse logic via inheritance; define contracts with abstract and interface.
Payable, receive & fallback (ETH flows)
Receive ETH via payable functions and the receive/fallback hooks.