t27.aiРусский

Local names: let and var

You will learn

When to use let and when var, and how a var is updated.

let a = w * h; gives a name to a value inside a function body. var i : u8 = 0; declares a name that may change, and i = i + 1; changes it. Use let when the value is computed once, var when a loop updates it. These names live only inside the function; the module level uses const.

Try it

Change let to var in area and check the verdict; then explain why let reads better there.

Open the interactive lesson →

t27 basics 13: let, var and const
t27 basics 13: let, var and const ↗

Where let, var and const live in a t27 spec and whether the name may change. Lesson 13 of the t27 basics course.

specs/basics/13_local_names.t27

// SPDX-License-Identifier: Apache-2.0
; t27 basics, lesson 13: Local names: let and var.
; Inside a function, let names a value once and var names one that changes.

module basics_13_local_names;

pub fn area(w: u16, h: u16) -> u16 {
    let a = w * h;
    return a;
}

pub fn count_up(n: u8) -> u8 {
    var i : u8 = 0;
    while (i < n) {
        i = i + 1;
    }
    return i;
}

pub const SIDE : u16 = 12;

test a_square_of_side_12 {
    assert SIDE * SIDE == 144;
}

Open the lesson's spec in the player ↗

All lessons