Lesson 2 of 15

Variables & Types

Variables in Zig

Zig has two ways to declare bindings: const and var. The distinction is simple and enforced by the compiler.

Constants with const

A const binding cannot be changed after initialization. If you do not need to mutate a value, always use const. The compiler will warn you if you use var when const would suffice.

const x: i32 = 42;
const name = "Zig"; // type inferred as *const [3:0]u8

Variables with var

A var binding can be reassigned:

var count: u32 = 0;
count += 1;

Type Annotations and Inference

You can explicitly annotate the type, or let the compiler infer it:

const explicit: i32 = 10;  // explicitly typed
const inferred = @as(i32, 10); // @as for explicit coercion

Basic Types

Zig has a rich set of primitive types. Unlike C, the sizes are explicit in the type name:

TypeDescription
u8, u16, u32, u64Unsigned integers
i8, i16, i32, i64Signed integers
f32, f64Floating-point numbers
boolBoolean (true or false)
usizePointer-sized unsigned integer
comptime_intCompile-time known integer (no fixed size)

The naming convention is clear: i for signed, u for unsigned, followed by the bit width. No ambiguity about sizes, ever.

As Spock would say: "Fascinating." Zig's type precision is entirely logical --- no room for ambiguity when the bit width is right there in the name.

Integer Literals

Zig supports several literal formats:

const decimal = 42;
const hex = 0xFF;
const octal = 0o77;
const binary = 0b1010;
const with_separators = 1_000_000; // underscores for readability

Type Coercion

Zig does not perform implicit type widening. If you have a u8 and need a u32, you must be explicit:

const small: u8 = 10;
const big: u32 = small; // OK: safe widening from u8 to u32

Widening to a larger type is allowed implicitly because no data can be lost. Narrowing requires an explicit @intCast.

Undefined

In Zig, you can declare a variable without initializing it by assigning undefined:

var buffer: [256]u8 = undefined;

This is explicitly opting into uninitialized memory. Zig never hides dangerous behavior behind defaults.

Your Task

Write a function describe that takes three parameters: a name of type []const u8, a year of type u16, and a typed boolean of type bool. The function should print them in the format:

name: <name>, year: <year>, typed: <typed>

followed by a newline.

For example, calling describe("Zig", 2016, true) should print: name: Zig, year: 2016, typed: true

Zig runtime loading...
Loading...
Click "Run" to execute your code.