Traits

// a trait names methods that types implement
trait Shape:
    fn area(self) -> float
    fn name(self) -> str
    // a method with a body is a default, which a type keeps unless it defines its own
    fn describe(self) -> str:
        ret self.name() + " of area " + str(self.area())

struct Circle:
    r: float

struct Rect:
    w: float
    h: float

impl Shape for Circle:
    fn area(self) -> float:
        ret 3.0 * self.r * self.r
    fn name(self) -> str:
        ret "circle"

impl Shape for Rect:
    fn area(self) -> float:
        ret self.w * self.h
    fn name(self) -> str:
        ret "rect"

// [T: Shape] lets the function call Shape's methods on any type that implements it
fn total[T: Shape](xs: list[T]) -> float:
    t = 0.0
    for x in xs:
        t += x.area()
    ret t

print(Circle(r=1.0).describe())
print(total([Circle(r=1.0), Circle(r=2.0)]), total([Rect(w=2.0, h=3.0)]))

// builtin types can implement a trait too
impl Shape for int:
    fn area(self) -> float:
        ret float(self * self)
    fn name(self) -> str:
        ret "square of side " + str(self)

print(total([1, 2, 3]), 4.describe())

// eq and ord are traits of the prelude: == and < use them, and so does sort
struct Version:
    major: int
    minor: int

impl ord for Version:
    fn cmp(self, other: Self) -> ordering:
        if self.major != other.major:
            ret self.major.cmp(other.major)
        ret self.minor.cmp(other.minor)

vs = [Version(major=1, minor=10), Version(major=0, minor=9), Version(major=1, minor=2)]
vs.sort()
print(vs[0], vs[2].minor, vs[0] < vs[1], 3.cmp(5))

// display is how print, str, and "{x}" write a value, wherever it appears
impl display for Version:
    fn display(self) -> str:
        ret "v{self.major}.{self.minor}"

print(vs, "newest: {vs[2]}")

fn largest[T: ord](xs: list[T]) -> T:
    best = xs[0]
    for x in xs:
        if x > best:
            best = x
    ret best

print(largest([3, 9, 4]), largest(["pear", "fig"]), largest(vs).minor)

prints

circle of area 3.0
15.0 6.0
14.0 square of side 4 of area 16.0
v0.9 10 true less
[v0.9, v1.2, v1.10] newest: v1.10
9 pear 10

Defining a trait

A trait names methods that several types can have. trait Shape: lists each method’s signature, fn area(self) -> float, without a body, and a type implements the trait with an impl Shape for Circle: block that defines each of them, with the same parameters and result. A method of the trait can also have a body, which is a default: every type that implements the trait gets it, unless its impl block defines the method itself, as Rect could with its own describe. A method of a trait you write takes self (only the prelude’s conversion traits, below, have methods without it), and inside a trait Self is the type that implements it, as in fn same(self, other: Self) -> bool.

Once a type implements a trait, its methods are called like any other: Circle(r=1.0).area(). A struct’s methods, inherent or from traits, all have different names, so a call never needs to say which trait it means.

Bounds

A generic function can say which traits its type parameters must implement, after a colon: fn total[T: Shape](xs: list[T]). Inside it, a value of type T has the methods of Shape, and nothing else, so the body is still checked once for every type T could be. A call checks that its types implement the traits: total([1.5]) is an error unless float implements Shape. A type parameter can have several bounds, as in [T: Shape + Named].

The compiler makes a copy of total for each type it is called with, so each call of area goes straight to the method of that type, with no lookup while the program runs.

Builtin types

int, float, bool, and str can implement traits too, in the file that defines the trait, so 4.describe() works once impl Shape for int: does.

Comparing and ordering

Two traits come with every program. eq is what == and != use. Every type == compares part by part implements it already, and a struct can say what equal means for it instead, with impl eq for Tag: and fn eq(self, other: Self) -> bool; that is also how a struct that holds a list becomes comparable. ord is what <, <=, >, >=, and sort use: int, float, str, and bytes implement it, and a struct can with fn cmp(self, other: Self) -> ordering, which returns one of less, equal, or greater. Bounds work with them too, so fn largest[T: ord] can use > on any ordered type, and [T: eq] lets a function use ==.

Sorting a list of a struct uses its cmp and keeps values it finds equal in the order they were in.

Every ord type also has three methods: a.min(b) and a.max(b) give the lesser and the greater of two values, and x.clamp(lo, hi) gives x kept between lo and hi, stopping the program if lo is greater than hi:

print(3.min(5), "pear".max("apple"), 12.clamp(0, 10))   // 3 pear 10

Writing values as text

A third trait, display, is how print, str, and a value in a string write a value. Every type implements it, which is why anything can be printed, and a struct can say how it is written instead, with impl display for Version: and fn display(self) -> str. Its text then appears wherever a Version does, inside a list or another struct too, as print(vs) shows above.

Converting between types

Two more traits of the prelude, from and try_from, say how a value becomes another type. Unlike the others, each has a type parameter, the type converted from, so a type can implement it once for each source type, as impl from[Celsius] for Fahrenheit: does:

struct Celsius:
    degrees: float

struct Fahrenheit:
    degrees: float

// a conversion that cannot fail
impl from[Celsius] for Fahrenheit:
    fn from(value: Celsius) -> Self:
        ret Fahrenheit(degrees=value.degrees * 9.0 / 5.0 + 32.0)

// and one that can
impl try_from[str] for Celsius:
    fn try_from(value: str) -> result[Self, str]:
        degrees = float(value)?
        if degrees < -273.15:
            ret err("colder than absolute zero")
        ret ok(Celsius(degrees=degrees))

fn read_all[T: try_from[str]](texts: list[str]) -> result[list[T], str]:
    out = []
    for text in texts:
        out.append(T(text)?)
    ret ok(out)

// what the result is used as says which type T is
fn total(texts: list[str]) -> result[int, str]:
    t = 0
    for n in read_all(texts)?:
        t += n
    ret ok(t)

fn temperatures(texts: list[str]) -> result[list[Celsius], str]:
    ret read_all(texts)

print(Fahrenheit(Celsius(degrees=100.0)))
print(Celsius("21.5"), Celsius("-300"), Celsius("warm"))
print(float(2), int(2.9), int("12"), str(Celsius(degrees=1.0)))
print(total(["1", "2"]), total(["1", "x"]), temperatures(["0", "37"]))

prints

Fahrenheit(degrees=212.0)
ok(Celsius(degrees=21.5)) err('colder than absolute zero') err("could not convert string to float: 'warm'")
2.0 ok(2) ok(12) Celsius(degrees=1.0)
ok(3) err("invalid literal for int() with base 10: 'x'") ok([Celsius(degrees=0.0), Celsius(degrees=37.0)])

A type called with one value converts it: Fahrenheit(c) calls the from above. A conversion that can fail is a try_from, whose try_from returns a result[Self, str], so Celsius("warm") is an err that ? passes on. A struct is still made with named values, as Celsius(degrees=1.0), so the two never look alike.

The builtin conversions work the same way. float(2) and str(x) cannot fail, while int(2.9), int("12"), and float("2.5") give results, since a float may be nan and text may not be a number at all. A bound such as [T: try_from[str]] lets generic code convert to its type parameter, as T(text)? does in read_all, where what each call’s result is used as says which type T is.

Next, Functions as values.