Skip to content

Generic traits and iteration

A trait can take type parameters: trait Convert<T> { fn convert(&self) -> T }. Each use with arguments (Convert<Str>) is its own trait, so it works everywhere a trait does: impl Convert<Str> for Label, bounds like fn show<T: Convert<Str>>(x: &T), Box<dyn Convert<Str>>, and generic impls like impl<T: Eq> Iterator<T> for Repeat<T>. A bound’s arguments can name other type parameters, and they are inferred from the impl: fn collect<T, I: Iterator<T>>(it: I) -> Vec<T> called with a Counter that implements Iterator<i64> gets T = i64.

Iterator<T> is built in, with one method fn next(&mut self) -> Option<T>. for x in it works on any type implementing it (the loop owns the iterator), on &mut it (the caller keeps it), and on Box<dyn Iterator<T>>; for (a, b) in it takes tuple items apart. It means while true { match it.next() { Some(x) => ..., None => break } }.

A trait method with a body is provided: implementers get it unless they write their own. It is compiled for each type that uses it, with Self as that type, so it can be generic and take self by value. dyn carries only the methods implementers must write.

The prelude, a module written in Brass and part of every program, defines Iterator<T> with provided adapters and consumers: map, filter, take, skip, enumerate, zip, chain, collect, count, fold, any, all, find, last:

fn upto(n: i64) -> Range {
return 1..n + 1
}
let squares = upto(5).map(fn(x) => x * x).collect()
print(squares.len())
let names = ["ann", "bob"]
for (i, name) in names.iter().enumerate() {
print(f"{i} {name}")
}
5
0 ann
1 bob

a..b is a value of the prelude type Range (from a up to, not including, b), and an Iterator<i64>: (0..10).step_by(3).rev(), (1..5).map(fn(x) => x * x), r.len(), r.contains(x). A for over a plain range compiles to a counting loop.

Collections hand out iterators: iter() borrows and yields references (&T, or (&K, &V) for a map), into_iter() takes the collection and yields its items. A borrowing iterator keeps its collection borrowed for as long as it is used, like any reference, so it cannot be returned past the collection or outlive a change to it. Your own structs can do the same: a struct Words { text: &Str, pos: i64 } implementing Iterator<Str> is a borrowing iterator over a string.

A closure passed to a generic function gets its parameter types from what is already known, so fn(x) => x * x needs no annotations here. Adapters store their closure, so it must capture by value.

A type can implement several traits whose methods share a name (say Convert<f64> and Convert<Str>). A call then uses the type’s own (inherent) method if it has one; otherwise the expected result type picks the trait (let f: f64 = c.convert()); inside a generic function the bound decides; anything still ambiguous is an error naming the candidates. Trait.method(x, ...) says exactly which trait is meant, with x as self: Convert<f64>.convert(&c), Named.shout(&c). It works for required and provided methods, generic impls, and inside generic functions.