LanguageAbstraction
13Implement Blocks
implement adds methods to a type without modifying its original declaration. There are three forms.
13.1 Inherent Implementation
Adds methods to a type. For a struct, an inherent block is interchangeable with declaring the methods inline:
implement struct Point {
distance_to(&this, other: Point) -> f64 {
const dx: f64 = (this.x - other.x) as f64;
const dy: f64 = (this.y - other.y) as f64;
return sqrt(dx * dx + dy * dy);
}
}
Inherent blocks are the only way to add methods to enums:
implement enum Color {
to_string(&this) -> string {
match (this) {
Color::Red => { return "red"; }
Color::Green => { return "green"; }
Color::Blue => { return "blue"; }
}
}
}
13.2 Trait Implementation
Provides the method bodies a trait requires for a specific type. Use this to make T participate in generic code that has a where T: SomeTrait bound.
implement trait Eq for i32 {
equals(&this, other: &i32) -> boolean {
return this == *other;
}
}
13.3 Implement Blocks on Primitives
Implement blocks may target primitive types, which is how the standard library hangs methods off boolean, the integer types, and string:
implement boolean {
to_i32(&this) -> i32 {
if (this) { return 1; }
return 0;
}
static default() -> boolean {
return false;
}
}
After the block is loaded, my_bool.to_i32() resolves like any other method call. Resolution is at compile time; no dynamic dispatch.