Mappings and structs
A mapping is a key-value store, ideal for balances and records. Every possible key exists and returns the default value, which is 0 for numbers and false for booleans, until you set something. Mappings do not store a list of their keys, so they cannot be looped over.
If you need to list the keys, keep a separate array next to the mapping and push each new key when it first appears. This costs a little more gas on writes but makes reading easy.
A struct groups related fields into one custom type. You can create one by naming the fields, which is clearer and safer than relying on their order. Structs can be stored in mappings and arrays to model users, orders or proposals.
Mappings can be nested, for example mapping(address => mapping(address => uint256)) for token allowances. To change a struct stored in a mapping, use a storage reference so you edit the original instead of a copy.
Deleting a mapping entry with delete resets it to the default value. It does not remove the key, because every key always exists.
contract Registry { struct User { string name; uint256 joined; bool active; } mapping(address => User) public users; mapping(address => mapping(address => uint256)) public allowance; address[] public userList; function register(string calldata n) external { require(bytes(users[msg.sender].name).length == 0, "Already registered"); users[msg.sender] = User({name: n, joined: block.timestamp, active: true}); userList.push(msg.sender); } function deactivate() external { User storage u = users[msg.sender]; // edit the original, not a copy u.active = false; } function approve(address spender, uint256 amount) external { allowance[msg.sender][spender] = amount; } function total() external view returns (uint256) { return userList.length; } }
Try it yourself
Add a function remove() that deletes the caller's entry from users. Then check what users(address) returns for someone who was never registered.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.