Skip to content

Traits

Contracts used by operators, collections, iteration, conversion, cleanup, and selection.

The stdlib’s traits connect generic algorithms and language syntax. Dispatch is static: generic uses are monomorphized for concrete types, and there is no current dyn Trait or vtable surface.

Trait Contract
Equatable Equality through equals
Hashable Hash consistent with equality
Comparable[T] Total ordering through compare_to, answering an Ordering
Display, Debug Human and developer text, written into a string
Numeric Arithmetic and numeric conversion
Neg, Not, BitNot Unary operators
BitAnd, BitOr, BitXor, Shl, Shr Bitwise operators
Index[K, V], IndexMut[K, V] Indexed read and write
Default, Clone Construction and copying
From[T], Into[T] Conversion
Iterator[T], Iterable[T] One-shot and repeatable iteration
Bytes, Buffer Byte views and builders
Drop User cleanup before storage release
Selectable[T] Value that can participate in select

Operator resolution uses direct primitive operations first and trait dispatch for user-defined operands.

struct Money { cents int }

impl Equatable for Money {
    fn equals(&self, other Money) bool {
        return self.cents == other.cents
    }
}

impl Display for Money {
    fn write_to(&self, out &mut string) void {
        out.append_int(self.cents)
        out.append(" cents")
    }
}

Collection bounds are meaningful: map keys and set members require Hashable; sorting requires Comparable; numeric aggregation requires Numeric. Implement the narrowest contracts a type actually satisfies.

Drop.drop runs as part of compiler-managed cleanup, including cancellation paths. It is for releasing external resources, not for manually balancing the compiler’s reference counts.

After the body returns, the compiler gives back every member the type declares, and the cycle collector reaches the same members. So a body that gives one of them back itself — with intrinsics.drop_in_place, take, shallow_release or dealloc — gives it back twice. A body may give back only what its type keeps hidden in a byte block (ptr[u8]), and only when the type declares nothing else that owns anything; anything else is ATOLL1091:

import intrinsics

struct Names {
    d ptr[string]
    @count n u32
    @capacity c u32
}

impl Drop for Names {
    fn drop(&self) void {
        unsafe { intrinsics.drop_in_place[string](intrinsics.to_raw[string](self.d)) }
    }
}

fn main() int { return 0 }

That rule is also what lets the collector run a Drop body for a collected cycle: what the body gives back is never a block the collector frees.

The stdlib also declares Trace, the cycle collector’s walk over a block the walk generated from a type’s fields cannot describe — Map’s table. It is the standard library’s own: only the standard library implements it, only the compiler calls it, and a program does not name it; a program’s own types are walked by their fields. An impl Trace in a program names no trait (ATOLL2104), and a program may declare a trait of its own called Trace:

struct Pair { a int, b int }

impl Trace for Pair {
    fn trace(&self, dir u32, parent usize) () {}
    fn trace_block(block rawptr[u8], slots usize, dir u32, parent usize) () {}
}

Ordering

enum Ordering { Less, Equal, Greater } is what a three-way comparison answers, and it is in the root namespace with no import. a.compare_to(b) answers one for numbers, char, string and any Comparable type, as does intrinsics.cmp(a, b); string.compare_to_ignore_case and float.total_compare answer one too.

Its methods read it as a bool — is_lt, is_le, is_gt, is_ge, is_eq, is_ne — or combine it: reverse() swaps Less and Greater, and a.then(b) is a unless a is Equal, which is how an order by several keys is written. A match names the three cases:

struct Version { major int, minor int }

impl Comparable[Version] for Version {
    fn compare_to(&self, other Version) Ordering {
        return self.major.compare_to(other.major).then(self.minor.compare_to(other.minor))
    }
}

fn describe(a Version, b Version) string {
    return match a.compare_to(b) {
        Less => "older"
        Equal => "same"
        Greater => "newer"
    }
}

fn main() void {
    a := Version { major: 1, minor: 4 }
    b := Version { major: 1, minor: 12 }
    println(describe(a, b))                           // older
    println("${a < b} ${a.compare_to(b).reverse().is_gt()}")   // true true
}

Comparable[T] also declares lt, le, gt and ge, which <, <=, > and >= call. Each has a default reading compare_to, so an impl writes only compare_to; it may write one of the four itself where it can answer more directly. A compare_to that answers int, the negative/zero/positive form of other languages, is refused (ATOLL2105).

Display writes into a string

Display has one required method, write_to(self, mut out ^string) void, which appends the value’s text to out. to_string() is a default written over it: it starts an empty string and calls write_to. Debug has the same shape, with write_debug_to required and debug_string() as the default.

Writing into the caller’s string is what keeps rendering free of intermediate strings. "${a} and ${b}" builds one string and asks each part to write itself into it, and a part that writes its own parts the same way — self.x.write_to(out) — adds no block of its own however deep the nesting goes. A List writes each element into the one string, and xs.join_to(out, ", ") and s.write_items_to(out) do the same for a separator-joined list and a set’s members. The builders an impl uses are append for a string, append_char, append_int, append_u64, append_u128, append_float and append_f32:

struct Span { start int, end int }

impl Display for Span {
    fn write_to(&self, out &mut string) void {
        self.start.write_to(out)
        out.append("..")
        self.end.write_to(out)
    }
}

fn main() void {
    spans := [Span { start: 0, end: 4 }, Span { start: 9, end: 12 }]
    mut line: string = "spans: "
    spans.join_to(&mut line, ", ")
    println(line)                       // spans: 0..4, 9..12
    println(spans.get(0)?.to_string() ?? "")  // 0..4
}

An impl Display that writes to_string instead is refused (ATOLL2105, missing write_to). A type with an inherent fn to_string and no impl Display still renders in "${x}", but does not satisfy a T: Display bound.

Contract laws

The type checker verifies signatures, not semantic laws. Implementations must preserve the laws expected by algorithms:

  • Equatable should be reflexive, symmetric, and transitive;
  • equal Hashable values must return the same hash code;
  • Comparable should agree with equality when compare_to answers Equal;
  • Clone should produce an independently usable value;
  • Display should remain suitable for users, while Debug can expose structure.

Violating equality and hashing laws can make map entries and set members unreachable even though the program still type-checks.

Operators

For non-primitive operands, syntax routes through trait methods:

Syntax Trait method
left == right Equatable.equals
left < right Comparable.lt (le, gt, ge for the others), by default from compare_to
-value Neg.neg
!value Not.not
left & right BitAnd.bit_and
left << amount Shl.shl
value[key] Index.get
value[key] = item IndexMut.set

Primitive numeric operations continue through direct compiler lowering. Implementing a trait does not replace those primitive paths.

Conversion

From[T] constructs the implementing type from T; Into[T] converts a receiver to T, giving the receiver away. Every From is an Into: write impl From[A] for B and a.into() is B.from(a), with no call left behind. Atoll does not apply arbitrary user conversions silently. Call conversion methods explicitly at API boundaries so allocation, failure, and precision changes remain visible.

Default.default() supplies a canonical zero or empty value. It does not imply that every instance can be reset safely by overwriting it with a default.

Iteration

Iterator[T] defines mutable next(): Option[T]; Iterable[T] creates an associated iterator. Default iterator methods implement traversal and lazy map/filter/take/skip adapters.

Byte protocols

Bytes exposes a pointer and length for read-only binary values. Buffer adds mutation and formatted appends. These traits let strings, lists, slices, and host APIs share binary operations without a separate nominal byte-buffer class.

Bytes is implemented by owned and borrowed byte sequences. Buffer is the growable super-surface implemented only by owned []byte.

Selection

Selectable[T] is structural:

trait Selectable[T] {
    fn raw_handle(&self) usize
    fn await(&self) T
}

Task[T] and Stream[T] satisfy it. Application implementations must also honor scheduler handle, readiness, and consumption invariants, so this is primarily a runtime extension point.

await() on a stream consumes its next item according to stream readiness; await() on a task waits for completion. select uses raw_handle() to register readiness with the scheduler before evaluating the winning arm.

Cleanup

Drop.drop cannot suspend: the trait declares it @nosuspend, and every implementation is held to that, through everything its body calls (ATOLL1071). Standard resource wrappers therefore make close synchronous even when their ordinary I/O methods can suspend. A custom Drop implementation must be safe to run during early return and error propagation.

See Traits for declarations, bounds, and associated types, and Implementations for coherence and method resolution.

Type to search…

↑↓ navigate↵ selectEsc close