Mappings, Structs and Arrays
Solidity's core data structures for organizing on-chain state, each with tradeoffs shaped by the fact that every operation costs gas.
Mappings
A mapping is a key-value store, Solidity's version of a hash map, but with a twist: it has no length, and no way to iterate over its keys, every possible key conceptually already exists, mapped to its type's default (zero) value:
mapping(address => uint256) public balances;
function deposit() public payable {
balances[msg.sender] += msg.value;
}
There's no "key not found" error, balances[someRandomAddress] simply returns 0 if nothing was ever set, exactly the same as if it had explicitly been set to zero.
Structs
struct Player {
string name;
uint256 xp;
bool active;
}
mapping(address => Player) public players;
function register(string memory name) public {
players[msg.sender] = Player(name, 0, true);
}
Mappings and structs combine constantly, exactly like the pattern above, associating a wallet address with a whole record of data about it.
Arrays
address[] public registeredPlayers;
function register2() public {
registeredPlayers.push(msg.sender);
}
Unlike mappings, arrays do have a length and can be iterated, but looping over a large on-chain array in a function costs gas proportional to its size, and can even become too expensive to call at all if it grows large enough. This is exactly why mappings, not arrays, are the default choice for most on-chain lookups.