liveBook · Manning

Struct

As explained in Systems Programming with Zig

A struct is a composite type that groups named fields and can also contain associated declarations or functions.

A Zig struct groups named fields into a single value. Fields can have different types, but each needs a unique name. Initialize the fields to create a value, then use dot syntax to access them. section 2.3

Listing 2.14 Declaring, instantiating, and using a struct
const std = @import("std");

const Point = struct { #1
    x: i32,
    y: i32,
};

pub fn main() void {
    const a: Point = .{ .x = 3, .y = -1 }; #2
    std.debug.print("x = {}, y = {}\n", .{a.x, a.y}); #3
}

Point groups two i32 coordinates, initializes them, and prints each field. section 2.3

A struct is a value: pass it to a function or use it as a field in another struct. A typed initializer such as `const a: Point = .{ .x = 3, .y = -1 };` and an explicit one such as `const a = Point{ .x = 3, .y = -1 };` are equivalent; the first form is preferred by the Zig community. section 2.3

Structs can also contain function or variable declarations. They can serve purely as namespaces, without grouping any data fields. section 2.3.1

Listing 2.15 Structs can have declarations
const std = @import("std");

// #1
const animal_noises = struct {
    // #2
    fn moo() void {
        std.debug.print("moo!\n", .{});
    }

    fn woof() void {
        std.debug.print("woof!\n", .{});
    }
};

pub fn main() void {
    // #3
    animal_noises.moo();
    animal_noises.woof();
}

The animal_noises struct collects two functions and calls them through the namespace. section 2.3.1

Source files define struct types too. Importing a Zig source file with `@import` returns a type whose declarations can be accessed as a namespace. section 2.3.1 section 2.1.4

Zig structs keep the feature set lean: fields and declarations, without inheritance or virtual method tables. Comptime can add capabilities to basic data structures beyond these fundamentals. section 2.3.4

How Systems Programming with Zig covers it

How deep it goes
Explains fields, initialization, access, and namespaces, while deferring further comptime capabilities.
Examples
Uses a two-coordinate Point and a namespace containing animal-noise functions.
What you can do after
Apply structs to group values, access fields, and organize functions under a namespace.
How it connects
Connects structs to namespaces, source files, imports, and comptime.

Also explained in

Compare how 16 books explain struct →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.