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
const stationinfers its type;const lamp_turns: u32states it.var oil_gallonscompiles only because the next line actually mutates it.- An unused variable or a never-mutated
varis a compile error, not a warning.
Keywords and builtins used here
constf32fnpubu32varvoid
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.
Step 2 of 3 in Values, step 2 of 27 in Language basics.