Docs/Language/Traits & Generics
Traits & Generics
cap declarations, default methods, bounds, associated types, and monomorphization.
~3 min read
On this page
Declaring and implementing a cap
Traits are declared with cap, the same keyword used for capabilities. A cap can give a default body for a method:
cap Greet {
fn name(self) -> str;
// Default method: implementors get it for free
fn greet(self) {
println("Hello from " + self.name());
}
}
struct Robot { id: i64 }
impl Greet for Robot {
fn name(self) -> str { return f"robot {self.id}"; }
}
fn main() -> i64 {
val r = Robot { id: 7 };
r.greet(); // Hello from robot 7
return 0;
}Associated types
The core library declares Iterator with an associated Item type:
struct Counter { count: i64, max: i64 }
impl Iterator for Counter {
type Item = i64;
fn next(self: &mut Counter) -> Option<i64> {
if self.count < self.max {
self.count += 1;
return Option::Some(self.count);
}
return Option::None;
}
}
fn main() -> i64 {
var c = Counter { count: 0, max: 2 };
println(c.next().unwrap()); // 1
println(c.next().unwrap()); // 2
println(c.next().is_some()); // false
return 0;
}Bounds
A bound such as T: Show or T: Named + Sized names caps the type must implement. It is checked at each call (example), and the methods of every listed cap can be called on T. Only caps that are declared somewhere are checked. Core declares Iterator and Error; there is no built-in Clone, Ord or Hash cap, so declare the caps you need.
Monomorphization and dyn
A generic function is compiled once per concrete type, with no boxing and no run-time dispatch. For run-time dispatch, convert a value to dyn Cap:
cap Animal {
fn legs(self) -> i64;
}
struct Dog { age: i64 }
struct Spider { venom: i64 }
impl Animal for Dog { fn legs(self) -> i64 { return 4; } }
impl Animal for Spider { fn legs(self) -> i64 { return 8; } }
// One compiled function; the call is dispatched at run time
fn count_legs(a: dyn Animal) -> i64 {
return a.legs();
}
fn main() -> i64 {
val dog = Dog { age: 3 } as dyn Animal;
val spider = Spider { venom: 1 } as dyn Animal;
println(count_legs(dog)); // 4
println(count_legs(spider)); // 8
return 0;
}Generic enums and impl blocks
An enum of your own can take type parameters, and the methods of impl<T> are typed per receiver: on a Slot<f64>, T is f64.
enum Slot<T> {
Full(T),
Empty,
}
impl<T> Slot<T> {
pub fn get_or(self: Slot<T>, other: T) -> T {
match self {
Slot::Full(v) => { return v; }
Slot::Empty => { return other; }
}
}
}
fn first<T>(xs: Vec<T>) -> T {
return xs.get(0);
}
fn main() -> i64 {
val a: Slot<f64> = Slot::Full(2.5);
val b: Slot<str> = Slot::Empty;
println(a.get_or(0.0)); // 2.5
println(b.get_or("none")); // none
var names: Vec<str> = Vec::new();
names.push("ada");
println(first(names)); // ada
return 0;
}A type parameter that nothing gives is an error (cannot infer the type parameter 'T' of 'make'); give the result a type (val z: i64 = zero();) or use a turbofish. A turbofish must give as many type arguments as the function has.
Not yet
- Literals of generic structs of your own (
Pair { first: 1, second: "one" }forstruct Pair<A, B>) work on the main branch since Nov 15; the v0.8.0 installer rejects them. - Type parameters on methods (core’s
mapisfn(T) -> T). whereclauses;impl<T> Show for Slot<T>(the type afterforis a single name).