Sub topic 14
Generic structs and methods
This chapter assumes you can define structs, write impl blocks, and use trait bounds in simple form (T: Trait).
Declaring a generic struct
A generic struct has a type parameter in angle brackets after its name. Every field that uses T holds the same concrete type.
#[derive(Debug)]
struct Point<T> {
x: T,
y: T,
}Point<i32> and Point<f64> are different types. The compiler generates a separate copy of the code for each concrete type you use (monomorphization), so generics add no runtime cost. To allow different types per field, declare more parameters, such as Point<T, U>.
Writing the impl block
The type parameter must be declared on impl as well as on the struct name:
impl<T> Point<T> {
fn new(x: T, y: T) -> Self {
Self { x, y }
}
fn x(&self) -> &T {
&self.x
}
}impl<T> introduces T. Point<T> then uses it. Without the first one, Rust would look for a type literally named T.
Methods for one concrete type
You can write an impl block for a single instantiation. These methods exist only on that type:
impl Point<f64> {
fn distance_from_origin(&self) -> f64 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
}
}Point<i32> has no distance_from_origin. Calling it is a compile error.
Bounds on impl blocks
When a method needs the type to support an operation, put a bound on the impl. Methods in that block exist only for types that satisfy it.
#[derive(Debug)]
struct Pair<T> {
a: T,
b: T,
}
impl<T: PartialOrd + Copy> Pair<T> {
fn larger(&self) -> T {
if self.a > self.b { self.a } else { self.b }
}
}PartialOrd allows >. Copy allows returning a field from behind &self without moving it.
Methods with their own parameters
A method can declare extra type parameters that belong to the method, not the struct:
impl<T> Pair<T> {
fn map<U, F: Fn(T) -> U>(self, f: F) -> Pair<U> {
Pair { a: f(self.a), b: f(self.b) }
}
}Here T comes from the struct and U and F come from the method. This block has no bounds on T, so it works for every Pair. Several impl blocks for the same struct are allowed.
fn main() {
let p = Point::new(3.0, 4.0);
println!("{}", p.distance_from_origin());
let q = Point::new(1, 2);
println!("{:?} {}", q, q.x());
let pair = Pair { a: 3, b: 7 };
println!("{}", pair.larger());
let scaled = pair.map(|n| n * 10);
println!("{:?}", scaled);
}This program prints 5, then Point { x: 1, y: 2 } 1, then 7, then Pair { a: 30, b: 70 }.
Common errors
- Forgetting
impl<T>. Writingimpl Point<T>gives "cannot find typeTin this scope". - Missing bound. Using
>on an unboundedTfails with "binary operation>cannot be applied to typeT". AddPartialOrdto theimpl. - Calling a bounded method on the wrong type. The error says the method exists but its trait bounds were not satisfied. Check which
implblock the method is in.
Exercise
You call larger() on Pair { a: String::from("x"), b: String::from("y") } and the compiler rejects it, even though String implements PartialOrd. Why, and what is one way to fix it?
Show answer
String is not Copy, so it fails the T: PartialOrd + Copy bound and that impl block does not apply. Either return a reference (fn larger(&self) -> &T in an impl<T: PartialOrd> block) or require Clone and return self.a.clone().