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
p = Point{x: 3, y: 4}
print(p.to_string()) // (3, 4)
print(p.x.to_string()) // 3Methods 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}"
}
}
cfg = Builder{name: "", port: 0}
.with_name("app")
.with_port(8080)
print(cfg.build()) // app:8080Impl 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 }
p = Person{name: "Alice", addr: Address{city: "NYC"}}
print(p.addr.city) // NYCStructs with Array Fields
wyn
struct Team {
name: string,
scores: [int]
fn total(self) -> int {
sum = 0
for s in self.scores { sum = sum + s }
return sum
}
}Function-Typed Fields
New in v1.21. A field can hold a function, so a struct can carry its own callback:
wyn
fn double(x: int) -> int { return x * 2 }
struct Op {
name: string,
apply: fn(int) -> int
}
fn main() {
o = Op { name: "double", apply: double }
println("${o.name} -> ${o.apply(21)}")
}The field's type is written the same way as any function type - fn(int) -> int - and it is called through the field: o.apply(21).
Field Mutation
wyn
p = Point{x: 1, y: 2}
p.x = 10
print(p.x.to_string()) // 10See Also
- Enums - algebraic data types
- Traits - shared behavior across types
- Pattern Matching - destructure structs in
match - Modules - organize structs into modules