Skip to content

Traits

Traits define shared behavior that structs can implement.

Defining a Trait

wyn
trait Drawable {
    fn draw(self) -> string
}

Implementing a Trait

Use impl Trait for Struct:

wyn
struct Circle { r: int }
struct Rect { w: int, h: int }

impl Drawable for Circle {
    fn draw(self) -> string { return "circle(${self.r})" }
}

impl Drawable for Rect {
    fn draw(self) -> string { return "rect(${self.w}x${self.h})" }
}

Dynamic Dispatch

Accept any type that implements a trait:

wyn
fn render(shape: Drawable) {
    println(shape.draw())
}

var c = Circle{r: 5}
var r = Rect{w: 10, h: 20}
render(c)   // circle(5)
render(r)   // rect(10x20)

Trait with Multiple Methods

wyn
trait Animal {
    fn name(self) -> string
    fn sound(self) -> string
}

struct Dog {}
impl Animal for Dog {
    fn name(self) -> string { return "Dog" }
    fn sound(self) -> string { return "Woof" }
}

struct Cat {}
impl Animal for Cat {
    fn name(self) -> string { return "Cat" }
    fn sound(self) -> string { return "Meow" }
}

MIT License