Zig, lesson 2
Zig wants you to be precise about your data. Every value has a type, and you choose how big your numbers are. That sounds like extra work, but it is how Zig produces fast programs with no surprises.
const and varconst names a value that never changes. Use it by default.var names a value you will change. Zig requires a type for a var declared inside a function,
written after a colon.The compiler is strict about both. If you declare a var but never change it, compilation fails
with "local variable is never mutated", telling you to use const. And a local or
that you never use is also an error. That can feel harsh, but it keeps code free of leftovers. If
you really want to ignore a value, assign it to : .
2 exercises to try what you just read.
constvar__ = lives;These rules apply inside functions. Declarations at the top of the file, outside any function, may go unused without complaint.
| Type | Holds | Example |
|---|---|---|
i32, i64 | signed whole numbers (32 or 64 bits) | -40 |
u8, u32, u64 | unsigned whole numbers (0 and up) | 200 |
usize | unsigned size of memory, used for lengths and indexes | 3 |
f64 | floating-point number | 36.6 |
bool | true or false | true |
[]const u8 | a string: a slice of bytes | "Ada" |
The number in a type name is its size in bits, so a u8 holds 0 to 255. Zig has no special string
type: a string is just a sequence of bytes, u8, and []const u8 means "a read-only slice of
bytes".
If a result does not fit its type, for example u8 going above 255 or a u32 going below 0, Zig
does not quietly wrap around. In a safe build the program stops with an "integer overflow" error
that points at the line. Choose types big enough for your data; i64 is a comfortable default for
everyday numbers.
A literal like 12 on its own is a comptime_int: a number known while compiling, with no fixed
size yet. It takes on a real type when it meets one, such as const total: u32 = 12 * 4;. That is
why const price = 12; needs no type.
Zig's style is snake_case for variables and constants (ticket_price), camelCase for functions
(printReceipt) and TitleCase for types. Names cannot be reused inside a function: declaring a
second price in the same scope, or one that shadows an outer price, is an error.
A cinema sells tickets for 12 euros each, and every order pays a booking fee of 3 euros. The
starter declares these as constants. For an order of 4 tickets, print:
Compute the total from the constants instead of typing 51 yourself. The program reads no input.
Start a balance at 100. Print it, then add a deposit of 50 and print it, then take away a
withdrawal of 30 and print it once more:
balance has to change, so it must be a var with a type (i64 is a good choice). The program
reads no input.
const price = 12; // can never change
var lives: u8 = 3; // can change
lives -= 1; // now 2Tickets: 4
Total: 51Start: 100
After deposit: 150
After withdrawal: 120