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
struct Treegroups a variety, a year, and a flag.Tree[] public treesgrows withpush.calldatastrings pass read-only from the caller.
Keywords and builtins used here
boolcontractexternalfalsefunctionpublicreturnreturnsstringstructuint16uint256
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.
Step 2 of 3 in Storage, step 6 of 28 in Language basics.