Skip to content

Structs

Defining a Struct

Fields use commas, methods use self:

wyn
struct Point {
    x: int,
    y: int

    fn magnitude_sq(self) -> int {
        return self.x * self.x + self.y * self.y
    }

    fn to_string(self) -> string {
        return "(${self.x}, ${self.y})"
    }
}

Creating Instances

wyn
var p = Point{x: 3, y: 4}
println(p.to_string())       // (3, 4)
println(p.x.to_string())     // 3

Methods Returning Self (Chaining)

Methods can return the struct type for fluent APIs:

wyn
struct Builder {
    name: string,
    port: int

    fn with_name(self, n: string) -> Builder {
        return Builder{name: n, port: self.port}
    }

    fn with_port(self, p: int) -> Builder {
        return Builder{name: self.name, port: p}
    }

    fn build(self) -> string {
        return "${self.name}:${self.port}"
    }
}

var cfg = Builder{name: "", port: 0}
    .with_name("app")
    .with_port(8080)
println(cfg.build())  // app:8080

Impl Blocks

Methods can also be defined outside the struct with impl:

wyn
struct Vec2 { x: int, y: int }

impl Vec2 {
    fn add(self, other: Vec2) -> Vec2 {
        return Vec2{x: self.x + other.x, y: self.y + other.y}
    }

    fn dot(self, other: Vec2) -> int {
        return self.x * other.x + self.y * other.y
    }
}

Nested Structs

wyn
struct Address { city: string }
struct Person { name: string, addr: Address }

var p = Person{name: "Alice", addr: Address{city: "NYC"}}
println(p.addr.city)  // NYC

Structs with Array Fields

wyn
struct Team {
    name: string,
    scores: [int]

    fn total(self) -> int {
        var sum = 0
        for s in self.scores { sum = sum + s }
        return sum
    }
}

Field Mutation

wyn
var p = Point{x: 1, y: 2}
p.x = 10
println(p.x.to_string())  // 10

See Also

MIT License