Skip to content

Zig Structs and Enums — Custom Data Types with Methods

DodaTech Updated 2026-06-29 1 min read

In this tutorial, you will learn about Zig Structs and Enums. We cover key concepts, practical examples, and best practices to help you master this topic.

Zig provides structs for grouping data and enums for type-safe constants. Both support methods, and switch on enums is checked exhaustively at compile time.

Structs

const User = struct {
    name: []const u8,
    age: u8,
    active: bool = true,

    pub fn init(name: []const u8, age: u8) User {
        return User{ .name = name, .age = age };
    }

    pub fn isAdult(self: User) bool {
        return self.age >= 18;
    }
};

const alice = User.init("Alice", 30);
std.debug.print("{}\n", .{alice.isAdult()});  // true

Enums

const Status = enum {
    ok,
    not_found,
    permission_denied,
    error,

    pub fn label(self: Status) []const u8 {
        return switch (self) {
            .ok => "Success",
            .not_found => "Not Found",
            .permission_denied => "Access Denied",
            .error => "Error",
        };
    }
};

const result: Status = .ok;
std.debug.print("{s}\n", .{result.label()});  // Success

// Switch must be exhaustive - compile error if not!

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro