Zig by Example
Zig by Example

Variables

< 1 min read

Variables

var declares a mutable binding. Every variable has to be initialized.

const std = @import("std");

pub fn main() void {
    var x: i32 = 1;
    x += 1;
    std.debug.print("x = {d}\n", .{x});

    // Type inference with var
    var y = @as(f32, 2.5);
    y *= 2.0;
    std.debug.print("y = {d}\n", .{y});
}

Zig won't compile a var that's never mutated — reach for const in that case.

Zig by Example
Zig by Example

by Dariush Abbasi

A hands-on introduction to Zig via annotated examples. Covers the language from Hello World through memory allocation, concurrency, networking, and C interop.

View book →