Traits

Traits

A trait is a set of method signatures a type can promise to provide.

[public] trait Plus<T> {
    fn plus(other: T) => T;
}

[public] trait Hash {
    fn hash() => number;
}

Signatures inside a trait end at the return type; there is no body.

Implementing

A class declares the traits it satisfies with impl and then defines the methods:

[public] class ArrayIterator<T> impl Iter<T> {
    // the methods Iter requires
}

The analyzer checks that every required method is present with a matching signature, and reports the ones that are missing.

Static trait methods

[static] declares a method with no receiver, called on the type rather than on an instance. Deserialization uses this: a type provides a static constructor that builds a value from a decoder.

[public] trait Deserialize {
    /// Read a new value of this type from `deserializer`.
    [static] fn deserialize(deserializer: Deserializer) => Self?;
}

Self inside a trait stands for the implementing type. Here the result is Self? because a decode can fail, so the caller checks before unwrapping.

Traits as bounds

The main use of a trait is constraining a generic parameter. See the generics page.

Traits as types

A trait can also be used as a type, in which case a value of any implementing class can be stored in it. Dispatch then goes through the witness table at runtime rather than being resolved statically.