TExcelTAD
Home › Solidity › Structs

Structs

A struct groups related values into one custom type, like a record or a lightweight class without methods. Structs model the "things" in a contract: a proposal, an order, a loan, a user profile.

solidity
struct Proposal {
    string description;
    uint256 yesVotes;
    uint256 noVotes;
    bool executed;
}

Creating structs

There are three ways to build a struct value:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    struct Task {
        string title;
        uint8 priority;
        bool done;
    }

    Task[] public tasks;

    function main() external {
        // 1. positional arguments, in declaration order
        tasks.push(Task("Write contract", 1, false));

        // 2. named fields: order-independent and clearer
        tasks.push(Task({done: false, title: "Write tests", priority: 2}));

        // 3. a zero-initialized variable, filled field by field
        Task memory t;
        t.title = "Deploy";
        t.priority = 3;
        tasks.push(t);

        for (uint256 i = 0; i < tasks.length; i++) {
            console.log(tasks[i].priority, tasks[i].title, tasks[i].done);
        }
    }
}
1 Write contract false
2 Write tests false
3 Deploy false

Prefer the named form when a struct has more than two or three fields: adding a field later then gives a compile error at every construction site instead of silently shifting values.

Updating stored structs

To modify a struct in storage, take a storage reference. A memory variable would be a copy (see Data Locations):

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract TodoList {
    struct Task { string title; bool done; }
    Task[] private tasks;

    function add(string calldata title) external returns (uint256 id) {
        tasks.push(Task(title, false));
        return tasks.length - 1;
    }

    function complete(uint256 id) external {
        Task storage task = tasks[id];
        require(!task.done, "already done");
        task.done = true;
    }

    function get(uint256 id) external view returns (Task memory) {
        return tasks[id];
    }

    function openCount() external view returns (uint256 count) {
        for (uint256 i = 0; i < tasks.length; i++) {
            if (!tasks[i].done) count++;
        }
    }
}

contract Main {
    function main() external returns (uint256) {
        TodoList list = new TodoList();
        list.add("buy milk");
        uint256 id = list.add("learn structs");
        list.add("call mom");
        list.complete(id);

        TodoList.Task memory t = list.get(id);
        console.log(t.title, "done?", t.done);
        return list.openCount();
    }
}
learn structs done? true
main() returned: 2

Functions can take and return structs; the ABI encodes them as tuples. From outside, TodoList.Task is referenced with the contract name as prefix.

Structs in mappings

A mapping from an id or address to a struct is the standard way to store records. Note how a missing key yields a struct of zero values, so an exists flag (or a non-zero field) tells you whether a record is real:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    struct Profile {
        string nickname;
        uint64 joinedAt;
        uint32 posts;
        bool exists;
    }

    mapping(address => Profile) public profiles;

    function register(address user, string memory nickname) internal {
        require(!profiles[user].exists, "already registered");
        profiles[user] = Profile({nickname: nickname, joinedAt: uint64(block.timestamp), posts: 0, exists: true});
    }

    function main() external {
        address ada = address(0xADA);
        register(ada, "ada");
        profiles[ada].posts += 3;

        Profile memory p = profiles[ada];
        console.log(p.nickname, p.posts, p.joinedAt);
        console.log("stranger exists?", profiles[address(0xBAD)].exists);

        register(ada, "ada again");
    }
}
ada 3 1767225600
stranger exists? false
main() failed: reverted with reason: already registered

Packing struct fields

Storage is organised in 32-byte slots. Consecutive fields smaller than 32 bytes share a slot when they fit. In Profile, joinedAt (8 bytes), posts (4 bytes) and exists (1 byte) all fit into one slot after the string's slot, so writing them is cheaper. Ordering fields from large to small, and grouping small ones, keeps a struct compact:

solidity
struct Wasteful { uint128 a; uint256 b; uint128 c; }   // 3 slots
struct Packed   { uint128 a; uint128 c; uint256 b; }   // 2 slots

Limitations

  • A struct cannot contain itself (no recursive types), but it can contain arrays of other structs and mappings.
  • A struct containing a mapping can only live in storage, and delete doesn't clear the mapping inside it.
  • Before declaring a huge struct, consider whether all fields really need to be on chain; emitting some data in events is far cheaper.

Test yourself

Why is Task({title: "x", priority: 1, done: false}) often preferred over Task("x", 1, false)?

  1. It uses less gas
  2. It's clearer and doesn't depend on field order
  3. Positional construction is deprecated
  4. It allows missing fields

What does reading profiles[unknownAddress] return if profiles is mapping(address => Profile)?

  1. It reverts
  2. A Profile with all fields set to zero values
  3. null
  4. The last registered profile

How many storage slots does struct S { uint128 a; uint128 b; uint256 c; } use?

  1. 1
  2. 2
  3. 3
  4. 4