Structs
Part of the Fundamentals section of Coddy's Solidity journey. Lesson 43 of 53.
A struct groups related fields under a custom type name. Each field has a type and a name, and fields may have different types. Declare the type at contract scope, create a value, then access its fields with a dot.
Declare this at contract scope:
struct Parcel { uint256 weight; bool ready; }Use it inside the provided main function:
Parcel memory item = Parcel(11, true);
console.log(item.weight);
console.log(item.ready);The Parcel type has weight and ready fields. The positional constructor supplies values in declaration order. This item lives in memory for the current call; declaring a struct type alone does not create stored records.
Use a dot followed by the field name to read or change a struct field.
Challenge
EasyDeclare a struct named Badge with uint256 level and bool active, in that order. Create a memory Badge from the supplied inputs and print both fields.
The tests pass arguments to main in this order: uint256 level, bool active. Each test starts with fresh contract state.
Use console.log for the requested output. Print only the requested values, one per line, with no extra labels unless the task specifies them.
Try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import "forge-std/console.sol";
contract Main {
function main(uint256 level, bool active) external view {
// Write your solution here.
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
Practice on your own: Solidity playground