Spec chapters

9. Structs and methods

const Point = struct {
    x: i64
    y: i64

    fn len2(self: Point) i64 { return self.x * self.x + self.y * self.y }
    fn move(inout self: Point, dx: i64) void { self.x = self.x + dx }
    fn origin() Point { return Point{ .x = 0, .y = 0 } }
}
  • A literal names every field exactly once (E123): Point{ .x = 1, .y = 2 }.
  • p.x reads a field (E122 if there is none); p.x = 3 assigns it when p is mutable.
  • A function inside a struct is a method if its first parameter has the struct’s type: p.len2() passes p by value; p.move(1) passes it as inout, so p must be a var or an inout parameter; a sink self method takes p over (section 21). Any function inside the struct can be called as Point.origin() or Point.len2(p).
  • A struct cannot contain itself by value (E119).
  • Field types may be anything except void, type and slices (E116).
// expect: 25
// expect: 4
uses io

fn main(io: Io) void {
    var p = Point.origin()
    p.move(3, 4)
    io.print(p.len2())
    io.print(p.y)
}

const Point = struct {
    x: i64
    y: i64

    fn origin() Point {
        return Point{ .x = 0, .y = 0 }
    }

    fn len2(self: Point) i64 {
        return self.x * self.x + self.y * self.y
    }

    fn move(inout self: Point, dx: i64, dy: i64) void {
        self.x = self.x + dx
        self.y = self.y + dy
    }
}