typestar

const and var in Zig

Zig polices both directions: const cannot change, var must.

const std = @import("std");

pub fn main() void {
    // const forbids reassignment; var demands mutation actually happen.
    const station = "Gull Rock";
    const lamp_turns: u32 = 148;
    var oil_gallons: f32 = 6.5;
    oil_gallons -= 1.25;

    std.debug.print("{s}: {d} turns tonight\n", .{ station, lamp_turns });
    std.debug.print("oil left: {d:.2} gallons\n", .{oil_gallons});
}

How it works

  1. const station infers its type; const lamp_turns: u32 states it.
  2. var oil_gallons compiles only because the next line actually mutates it.
  3. An unused variable or a never-mutated var is a compile error, not a warning.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
362
Tokens
81
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 69 seconds.

Type this snippet

Step 2 of 3 in Values, step 2 of 27 in Language basics.

← Previous Next →