Version: 1.1.0

Traits

A trait names behavior. A struct conforms by implementing the required methods. Generic code then accepts any conforming type.

Essentials

  • Declare methods in the trait and leave the body as ....
  • A struct lists traits in parentheses: struct Point(Equatable).
  • A parameter constraint looks like T: Equatable.
  • Traits can provide default methods.
  • Copyable & Movable requires both.

Example

trait Greetable:
    fn greet(self) -> String:
        ...

struct Bot(Greetable):
    fn greet(self) -> String:
        return "beep"

fn hello[T: Greetable](value: T):
    print(value.greet())

Keep in mind

Traits are static. There is no vtable unless you opt into a dynamic type. That is why generic calls still inline.