t27.aiРусский

Enums

You will learn

The two ways to declare an enum and how a switch reads a value.

pub enum Color { Red, Green, Blue } names three cases. The Zig form pub const Mode = enum(u8) { Idle, Run } also fixes the type that stores a case, here u8. A switch over a value lists what each case gives and uses else for the rest. Both forms compile clean on all 7 backends in the lesson spec.

Try it

Add a fourth color to Color and update CASES_IN_COLOR so the test passes.

Open the interactive lesson →

t27 basics 18: two ways to write an enum
t27 basics 18: two ways to write an enum ↗

The two enum forms the t27 compiler accepts, side by side with their cases. Lesson 18 of the t27 basics course.

specs/basics/18_enums.t27

// SPDX-License-Identifier: Apache-2.0
; t27 basics, lesson 18: Enums.
; An enum names a fixed set of cases, and switch picks one of them.

module basics_18_enums;

pub enum Color {
    Red,
    Green,
    Blue,
}

pub const Mode = enum(u8) {
    Idle,
    Run,
};

pub const CASES_IN_COLOR : u8 = 3;

test color_has_three_cases {
    assert CASES_IN_COLOR == 3;
}

Open the lesson's spec in the player ↗

All lessons