t27.aiРусский

Structs

You will learn

How to declare a struct and a packed struct, and how many a module may hold.

pub struct Point { x: i32, y: i32 } declares a type with two fields. Fields are a name and a type, separated by commas. A packed struct lays its fields next to each other with no padding, the shape a hardware register has. A module may declare several structs; the lesson spec has two, and the verdict stays clean on all 7 backends.

Try it

Add a field z: i32 to Point and check which backends still compile it.

Open the interactive lesson →

t27 basics 17: a struct and its fields
t27 basics 17: a struct and its fields ↗

A t27 struct and a packed struct drawn as tables of fields, with how many backends compiled them. Lesson 17 of the t27 basics course.

specs/basics/17_structs.t27

// SPDX-License-Identifier: Apache-2.0
; t27 basics, lesson 17: Structs.
; A struct groups named fields, each with its own type.

module basics_17_structs;

pub struct Point {
    x: i32,
    y: i32,
}

pub const Flags = packed struct {
    ready: bool,
    error: bool,
};

pub const FIELDS_IN_POINT : u8 = 2;

test a_point_has_two_fields {
    assert FIELDS_IN_POINT == 2;
}

Open the lesson's spec in the player ↗

All lessons