typestar

Structs and arrays in Solidity

Bundle fields, then push them into a growing list.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

// Structs bundle fields; dynamic arrays grow with push.
contract TreeRegistry {
    struct Tree {
        string variety;
        uint16 plantedYear;
        bool bearing;
    }

    Tree[] public trees;

    function plant(string calldata variety, uint16 year) external {
        trees.push(Tree(variety, year, false));
    }

    function count() external view returns (uint256) {
        return trees.length;
    }
}

How it works

  1. struct Tree groups a variety, a year, and a flag.
  2. Tree[] public trees grows with push.
  3. calldata strings pass read-only from the caller.

Keywords and builtins used here

The run, in numbers

Lines
21
Characters to type
410
Tokens
73
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 73 seconds.

Type this snippet

Step 2 of 3 in Storage, step 6 of 28 in Language basics.

← Previous Next →