t27.aiРусский

Choices: if, else and switch

You will learn

The forms of if the compiler accepts, the if expression, and switch with else.

if (a > b) { ... } else { ... } runs one of two blocks. The parentheses are optional: if a > b { ... } also compiles. if can be an expression too: return if (a > b) a else b; gives the larger one. switch (m) { 0 => 10, else => 20 } picks a value by matching m, and else covers every other case.

Try it

Add a case 1 => 15 to the switch in the player and check the verdict.

Open the interactive lesson →

t27 basics 14: the shapes of a choice
t27 basics 14: the shapes of a choice ↗

Every form of if and switch the t27 compiler accepts, each checked with the real compiler. Lesson 14 of the t27 basics course.

specs/basics/14_if_and_else.t27

// SPDX-License-Identifier: Apache-2.0
; t27 basics, lesson 14: Choices: if, else and switch.
; if picks one of two paths; switch picks one of many by value.

module basics_14_if_and_else;

pub fn larger(a: u8, b: u8) -> u8 {
    if (a > b) {
        return a;
    } else {
        return b;
    }
}

pub fn larger_expr(a: u8, b: u8) -> u8 {
    return if (a > b) a else b;
}

pub fn price(m: u8) -> u8 {
    return switch (m) {
        0 => 10,
        else => 20,
    };
}

pub const LIMIT : u8 = 10;

test the_limit_is_ten {
    assert LIMIT == 10;
}

Open the lesson's spec in the player ↗

All lessons