0PricingLogin
Zig Academy · Lesson

Methods and the self Parameter

Attach behavior to your structs.

Data Plus Behavior

A struct can hold more than fields. You can declare methods inside it: functions that act on the data they belong to.

Functions Live Inside

Write a normal fn inside the struct body. It becomes namespaced under the type, callable as Type.name.

const Point = struct {
    x: i32,
    y: i32,
    fn origin() Point {
        return Point{ .x = 0, .y = 0 };
    }
};

All lessons in this course

  1. Declaring Structs and Fields
  2. Methods and the self Parameter
  3. Default Field Values
  4. Anonymous Structs and Tuples
← Back to Zig Academy