Sub topic 14
Generic Structs and Methods
This chapter assumes you can define structs and write impl blocks with &self and &mut self methods. You should also know the basics of traits and trait bounds such as T: Display. A generic struct lets one definition hold different types. You will write them, attach methods in several ways, and learn the errors that show up most often.
A struct with a type parameter
A type parameter is a placeholder written in angle brackets after the struct name. Each use of the struct replaces the placeholder with a real type.
#[derive(Debug)]
struct Point<T> {
x: T,
y: T,
}
fn main() {
let a = Point { x: 3, y: 4 };
let b = Point { x: 1.5, y: 2.5 };
println!("{:?} {:?}", a, b);
}Here a is a Point<i32> and b is a Point<f64>. Both fields share the single parameter T, so Point { x: 3, y: 2.5 } does not compile. The compiler infers T = i32 from the first field and rejects the float in the second.
For fields of different types, add a second parameter: struct Mixed<T, U> { a: T, b: U }.
Generic impl blocks
To add methods, declare the parameter twice: once after impl and once on the type.
#[derive(Debug)]
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn new(x: T, y: T) -> Self {
Self { x, y }
}
fn x(&self) -> &T {
&self.x
}
}
fn main() {
let p = Point::new(10, 20);
println!("{}", p.x());
}The first <T> in impl<T> says that T is a parameter of this block. The second, in Point<T>, says the block applies to Point for any T. Without the first <T>, Rust would look for a type literally named T and fail.
The getter returns &T rather than T. Returning T would try to move or copy the field out of a borrowed struct, and that is only allowed for Copy types. A generic T makes no such promise.
Methods for one concrete type
An impl block can name a concrete type instead of a parameter. Its methods exist only for that type.
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn new(x: T, y: T) -> Self {
Self { x, y }
}
}
impl Point<f64> {
fn distance_from_origin(&self) -> f64 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
}
}
fn main() {
let p = Point::new(3.0, 4.0);
println!("{}", p.distance_from_origin());
}This prints 5. A Point<i32> has no distance_from_origin, and calling it is a compile error. This is useful when an operation only makes sense for certain types, such as floating-point math.
Bounded impl blocks
Often you want a method for every T that has certain capabilities. Put the trait bounds on the impl.
struct Pair<T> {
a: T,
b: T,
}
impl<T> Pair<T> {
fn new(a: T, b: T) -> Self {
Self { a, b }
}
}
impl<T: PartialOrd + Copy> Pair<T> {
fn larger(&self) -> T {
if self.a > self.b { self.a } else { self.b }
}
}
fn main() {
let nums = Pair::new(3, 7);
println!("{}", nums.larger());
let words = Pair::new(String::from("a"), String::from("b"));
let _ = (&words.a, &words.b);
}Pair::new works for any type, including String. larger needs PartialOrd to compare and Copy to return a value from &self. A Pair<String> is valid, but calling words.larger() fails with an error saying the method exists but its trait bounds were not satisfied.
Put bounds on impl blocks, not on the struct definition. A bound on the struct, as in struct Pair<T: PartialOrd>, forces every mention of Pair<T> to repeat it, even in code that never compares anything.
Methods with their own parameters
A method can introduce type parameters beyond those of the struct.
#[derive(Debug)]
struct Mixed<T, U> {
a: T,
b: U,
}
impl<T, U> Mixed<T, U> {
fn swap(self) -> Mixed<U, T> {
Mixed { a: self.b, b: self.a }
}
fn mix<V, W>(self, other: Mixed<V, W>) -> Mixed<T, W> {
Mixed { a: self.a, b: other.b }
}
}
fn main() {
let m = Mixed { a: 1, b: "one" };
println!("{:?}", m.swap());
let left = Mixed { a: 'x', b: 2.5 };
let right = Mixed { a: true, b: "end" };
println!("{:?}", left.mix(right));
}The output is Mixed { a: "one", b: 1 } and then Mixed { a: 'x', b: "end" }. T and U belong to the impl. V and W belong only to mix, and the compiler infers them from the argument.
A practical example: a generic stack
Most standard library containers are generic structs wrapping a field of type T.
#[derive(Debug)]
struct Stack<T> {
items: Vec<T>,
}
impl<T> Stack<T> {
fn new() -> Self {
Self { items: Vec::new() }
}
fn push(&mut self, item: T) {
self.items.push(item);
}
fn pop(&mut self) -> Option<T> {
self.items.pop()
}
fn peek(&self) -> Option<&T> {
self.items.last()
}
fn len(&self) -> usize {
self.items.len()
}
}
fn main() {
let mut s = Stack::new();
s.push("a");
s.push("b");
println!("{:?} {}", s.peek(), s.len());
println!("{:?}", s.pop());
let empty = Stack::<u8>::new();
println!("{:?}", empty);
}peek returns Option<&T> because it only borrows. pop returns Option<T> because it gives up ownership. The last two lines show a common error. Stack::new() alone gives the compiler no way to pick T, so you must supply it. You can annotate the variable (let s: Stack<u8> = Stack::new();) or use the turbofish, Stack::<u8>::new().
How generics are compiled
Rust uses monomorphization. For each concrete type you use, the compiler generates a separate copy of the struct and its methods.
There is no runtime cost and no boxing. The cost is compile time and binary size, which grow with the number of distinct types you instantiate. Two instantiations such as Stack<i32> and Stack<String> are unrelated types. You cannot pass one where the other is expected.
Derives and generics
A derive on a generic struct adds a bound on each parameter. #[derive(Debug, Clone)] on Stack<T> generates impl<T: Debug> Debug and impl<T: Clone> Clone. So Stack<T> is Debug only when T is. This usually behaves as you want. It can surprise you with Default. #[derive(Default)] requires T: Default, even when your Default would only create an empty Vec<T>. If you hit this, write that impl by hand.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `cannot find type T in this scope` | Missing `<T>` after `impl` | Write `impl<T> Point<T>` |
| `expected i32, found floating-point number` | Two fields share one parameter | Add a second parameter `U` |
| `type annotations needed` | Nothing determines `T` | Annotate the variable or use `::<Type>` |
| Method exists but bounds not satisfied | `T` lacks a trait required by the `impl` block | Implement the trait or use a different type |
| `cannot move out of borrowed content` in a getter | Returned `T` from `&self` | Return `&T`, or add `T: Clone` and clone |
Exercise
Why does impl Point<f64> { ... } not need <T> after impl, while impl<T> Point<T> { ... } does?
Show answer
In impl Point<f64> the type is concrete, so no parameter is being introduced. In impl<T> Point<T>, T is a new name that the block declares. Without the declaration, Rust would treat T as an unknown type.
Exercise
Add a method sum(&self) -> T to Pair<T> that returns a + b. Which bounds does the impl block need, and why?
Show answer
Use impl<T: std::ops::Add<Output = T> + Copy> Pair<T> { fn sum(&self) -> T { self.a + self.b } }. Add<Output = T> lets + produce a T. Copy lets you read self.a and self.b out of a &self without moving them.