Types and traits
trait Show { fn show(&self) -> Str}
struct Stack<T> { items: Vec<T>}
impl<T> Stack<T> { fn push(&mut self, item: T) { self.items.push(item) }}
impl<T: Show> Show for Stack<T> { fn show(&self) -> Str { let mut parts: Vec<Str> = [] for item in &self.items { parts.push(item.show()) } return "[" + parts.join(", ") + "]" }}
struct Point { x: i64}
impl Show for Point { fn show(&self) -> Str { return "P" + self.x.to_str() }}
fn show_all<T: Show>(items: &Vec<T>) -> Str { let mut out = "" for item in items { out.push(item.show()) } return out}
let mut s: Stack<Point> = Stack { items: [] }s.push(Point { x: 1 })s.push(Point { x: 2 })print(s.show())print(show_all(&s.items))-
Generic functions, structs and enums take type parameters with trait bounds (
<T: Show + Eq>). -
A generic body is type-checked once, against its bounds: a type parameter only has the methods its bounds declare. Errors show up even if the function is never called.
-
Type arguments are inferred from the arguments, the field values and the expected type, never from later uses:
let s: Stack<i64> = Stack.new(). -
Generics are monomorphized: each instantiation is compiled separately.
-
Box<dyn Trait>and&dyn Traitgive dynamic dispatch through a vtable.Box<T>and&Tconvert to them automatically where expected. Only traits whose methods take&self/&mut selfand never mentionSelfcan be used withdyn. Values holdingdyncannot be cloned. -
Methods can only be added in the module that defines the type, or in the module that defines the trait being implemented.
-
An
implof a trait must provide exactly the trait’s methods, with the same signatures. -
No null: use
Option. -
No implicit conversions (no numeric widening, no truthiness).
-
No class inheritance. Behaviour is shared through Rust-style traits:
trait,impl Trait for Type, generics with trait bounds, and explicitdynfor dynamic dispatch. -
Integer overflow and division by zero stop the program; they are never silently wrapped or undefined.
-
f64follows IEEE 754 (division by zero givesinf). Integers and floats never mix implicitly: convert withi.to_f64()andx.to_i64()(which stops the program if the value does not fit). -
Pattern matching is exhaustive. Enum variants are always written with their type (
Shape.Circle(r)), so it is always clear where a name comes from. -
No shadowing: a name can be declared only once in a function, including in nested blocks.
-
A returned value cannot be silently dropped; discard it with
let _ = f(). -
Comparisons cannot be chained (
a < b < cis an error), and&&mixed with||needs parentheses:(a && b) || c. -
Conditions must be
bool; there is no truthiness. -
Statements end at the end of a line (Go’s rule), or with
;. -
Integer division truncates toward zero.