Traits
Interfaces, implementations, Self, defaults, bounds, composition, and generic targets.
Contents
A trait declares a set of related methods that a type can provide. Traits are how Haze expresses shared behaviour across unrelated types without inheritance. They are statically resolved: there is no trait object, no dynamic dispatch, and no runtime method table.
Declaring a Trait#
A trait declaration contains method signatures and, optionally, default bodies. Methods may be marked pub and pure, and may carry contracts.
trait Eq {
pub fn eq(x, y Self) bool
pub fn neq(x, y Self) bool {
return !x.eq(y)
}
}
Self stands for the type that implements the trait. In a trait method, the first parameter may omit its type; an omitted type means Self. A subsequent parameter must be written explicitly.
trait Number[T] {
pub fn add(x, y T) T
pub fn sub(x, y T) T
}
The trait above is parameterized by T, but its methods use T directly rather than Self. A trait may mix Self and its own type parameters when the operation relates several types.
Implementing a Trait#
An implementation names the target type first, then of, then the trait and any trait arguments. The methods provide the bodies for the declarations.
impl i32 of Eq {
pub fn eq(x, y Self) bool => x == y
}
impl Account of Eq {
pub fn eq(x, y Self) bool => x.id == y.id
}
The target may be a built-in type, a record, a refinement type, a generic instantiation, or a parameterized built-in such as List[i32]. The implementation is not a member of the target type's declaration; it can live in another module, provided the trait is visible.
trait Size {
pub fn size(x Self) i64
}
impl List[i32] of Size {
pub fn size(x Self) i64 => cast[i64](x.len)
}
impl str of Size {
pub fn size(x Self) i64 => cast[i64](x.len)
}
An implementation method may have its own contracts. Trait method declarations may also carry contracts; those clauses are copied onto an implementation method automatically, with the trait parameter names mapped to the implementation's names. The implementation may add further clauses. This makes the trait declaration's obligations apply to every implementation without repeating the clauses by hand.
Calling Trait Methods#
A method is called with method syntax on the receiver. The receiver becomes the first argument.
fn main() {
var left = Account { id = 1, balance = 100 }
var right = Account { id = 1, balance = 50 }
print(left.eq(right))
print(left.neq(right))
}
Method resolution first looks for a trait implementation whose target matches the receiver type and whose method name matches. If none is found, the compiler falls back to an ordinary free function with the same name and the receiver as its first parameter. This is why a free function and a trait method can share a call syntax without conflict.
Default Methods#
A method with a body in the trait declaration is a default method. An implementation may inherit it or override it.
trait Counter[T] {
pub fn base(x T) i64
pub fn doubled(x T) i64 {
return x.base() * 2
}
pub fn reset(x T) T {
return Self { value = 0 }
}
}
type Box {
value i64
}
impl Box of Counter {
pub fn base(x Self) i64 => x.value
}
Box.doubled() calls the default method, which in turn calls the overridden base. Box.reset() constructs a Self value, so the default can be written once and reused by every implementing type. An implementation may override a default when the generic definition is not the best one.
impl Box of Counter {
pub fn base(x Self) i64 => x.value
pub fn label(x Self) str => "custom"
}
Bounds#
A bound makes a trait's methods available on a type parameter. It is written after the parameter name, with a space rather than a colon.
fn largest[T Ord](a T, b T) T {
if a.lt(b) {
return b
}
return a
}
The bound is checked when largest is instantiated. Both Box and i32 can be passed if both have an Ord implementation. A parameterized bound uses brackets.
trait Convert[A] {
pub fn convert(x Self) A
}
fn read[T Convert[i64]](value T) i64 => value.convert()
A function may have several type parameters, each with its own bound. Bounds can also refer to a composed trait, in which case the methods of every base trait are available.
Trait Composition#
A trait may extend one or more base traits. The colon introduces the bases, and the composed trait inherits their method declarations and default methods.
trait Eq {
pub fn eq(x, y Self) bool
pub fn neq(x, y Self) bool {
return !x.eq(y)
}
}
trait Ord : Eq {
pub fn lt(x, y Self) bool
pub fn largest(x, y Self) Self {
if x.lt(y) {
return y
}
return x
}
}
An implementation of Ord must provide lt and eq, because Eq is a base. It inherits neq and largest. A bound of T Ord therefore exposes all four methods.
type Box {
value i64
}
impl Box of Ord {
pub fn eq(x, y Self) bool => x.value == y.value
pub fn lt(x, y Self) bool => x.value < y.value
}
fn same[T Ord](a T, b T) bool => a.eq(b)
Parameterized bases use explicit arguments, as in trait Derived[B] : Base[B]. The arguments are substituted into the base methods when the composed trait is instantiated.
Generic Traits and Explicit Arguments#
A generic trait is declared with type parameters and implemented with concrete arguments. The target may be generic as well.
trait Sum[T] {
pub fn sum(x, y T) T
}
impl Box[i64] of Sum {
pub fn sum(x, y Self) Self => Self { value = x.value + y.value }
}
When the trait has one type parameter and the implementation does not write it, the compiler can often infer it from Self or from the method signatures. When the trait has several parameters, write the arguments explicitly to avoid ambiguity.
trait Convert[A] {
pub fn convert(x Self) A
}
impl Meter of Convert[Meter, i64] {
pub fn convert(x Self) i64 => x.value
}
The exact arity must match the trait declaration. An implementation with the wrong number of trait arguments is rejected.
Implementations for Refinements and Built-ins#
A refinement type is a distinct target. An implementation for Positive does not apply to i64, and an implementation for i64 does not apply to Positive.
trait Ord {
pub fn lt(x, y Self) bool
}
type Positive = i64 : invariant self > 0
impl Positive of Ord {
pub fn lt(x, y Self) bool => x < y
}
Built-in targets are useful for adapting standard operations to the trait vocabulary. An implementation for List[i32] applies only to lists of i32; a separate implementation is needed for List[str].
External Implementations#
The entry module may implement its own trait for a type imported from another module. This is useful for adapting a library type to a local abstraction without modifying the library.
use lib/trait_types {Quantity}
trait Sum[T] {
pub fn sum(x, y T) T
}
impl Quantity of Sum {
pub fn sum(a, b Self) Self => Self { value = a.value + b.value }
}
The target type must be visible, and the trait must be in scope. The implementation does not change the type's declaration; it adds a method set that the compiler can resolve in the current program.
Static Resolution#
Trait calls are resolved at compile time. There is no dyn type, no virtual table, and no mechanism for storing a value of an unknown implementing type. This is a deliberate trade: generic code is monomorphized and fast, and the set of implementations is visible to the compiler.
The cost is that a trait cannot be used as a runtime interface for heterogeneous collections. Model a heterogeneous collection with a sum type whose variants carry the different concrete types, then match on the variant and call the appropriate method. The Sum Types and Enums chapter shows the pattern.
Summary#
| Feature | Rule |
|---|---|
| Declaration | trait Name { fn method(...) ... } |
| Self | The implementing type; first parameter may omit its type |
| Implementation | impl Target of Trait[args] { ... } |
| Default method | A method with a body in the trait declaration |
| Override | Provide the method again in the implementation |
| Bound | T Trait or T Trait[args] on a function type parameter |
| Composition | trait Derived : Base, Other |
| Built-in target | Allowed, including parameterized targets |
| Refinement target | Allowed; distinct from the base type |
| Dynamic dispatch | Not supported |
| Associated types | Not supported |