kota's memex

Definition

A basic, public struct definition looks like this:

pub const User = struct {
    power: u64,
    name: []const u8,
};

Struct fields are terminated with a comma and can be given a default value:

pub const User = struct {
	power: u64 = 0,
	name: []const u8,
};

When we create a struct, every field (without a default) has to be set. For example, in the original definition, where power had no default value, the following would give an error: missing struct field: power

const user = User{.name = "Goku"};

Methods

Structs can have methods, they can contain declarations (including other structs) and they might even contain zero fields, at which point they act more like a namespace.

pub const User = struct {
	power: u64 = 0,
	name: []const u8,

	pub const SUPER_POWER = 9000;

	fn diagnose(user: User) void {
		if (user.power >= SUPER_POWER) {
			std.debug.print("it's over {d}!!!", .{SUPER_POWER});
		}
	}
};

Methods are just normal functions that can be called with a dot syntax. Both of these work:

// call diagnose on user
user.diagnose();

// The above is syntactical sugar for:
User.diagnose(user);

Init method

Above diagnose was defined within our User type and accepts a User as its first parameter. As such, we can call it with the dot syntax. But functions within a structure don't have to follow this pattern. One common example is having an init function to initiate our structure:

pub const User = struct {
	power: u64 = 0,
	name: []const u8,

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