Skip to content
Solidity

Mappings, Structs & Nested Storage

Group related data with structs and look it up by key with mappings.

By EZ4Code Team
mappingstructstorage

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