Sub topic 6
Generic impl blocks and specialized impls
This chapter assumes you can write generic structs like Point<T>, you know the T: Trait bound syntax, and you can implement a trait for a type. It covers how to write methods for generic types, and how to give some instantiations methods that others lack.
Declaring parameters on an impl block
A method on Point<T> has to say what T is. The impl keyword takes its own parameter list, and that list declares the names the rest of the block uses.
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn new(x: T, y: T) -> Self {
Point { x, y }
}
fn x(&self) -> &T {
&self.x
}
}
fn main() {
let p = Point::new(1, 2);
let q = Point::new("a", "b");
println!("{} {}", p.x(), q.x());
}There are two <T> here, and they do different jobs. The first, in impl<T>, declares T. The second, in Point<T>, uses it. If you leave out the first one, the compiler reads T as the name of a concrete type and reports that it cannot find it.
Inside the block, Self is shorthand for Point<T>. Every Point<i32>, Point<&str>, or Point<Vec<u8>> gets these methods.
Specialized impls
An impl block can also name a concrete type in place of the parameter. The methods in that block exist only for that instantiation.
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn new(x: T, y: T) -> Self {
Point { x, y }
}
fn x(&self) -> &T {
&self.x
}
}
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.x(), p.distance_from_origin());
let q = Point::new(1, 2);
println!("{}", q.x());
}impl Point<f64> has no parameter list, because it introduces no names. The body can call powi and sqrt because self.x is known to be an f64. A generic T would not allow that.
Calling q.distance_from_origin() on a Point<i32> is a compile error. The method does not exist for that type. The standard library uses the same pattern. Result<Option<T>, E> has a transpose method that Result<T, E> does not have, and it lives in an impl<T, E> Result<Option<T>, E> block.
Methods with their own type parameters
A method can declare parameters beyond those of its impl block. These belong to the single method, not to the type.
struct Point<X, Y> {
x: X,
y: Y,
}
impl<X1, Y1> Point<X1, Y1> {
fn mixup<X2, Y2>(self, other: Point<X2, Y2>) -> Point<X1, Y2> {
Point {
x: self.x,
y: other.y,
}
}
}
fn main() {
let a = Point { x: 5, y: 10.4 };
let b = Point { x: "Hello", y: 'c' };
let c = a.mixup(b);
println!("{} {}", c.x, c.y);
}X1 and Y1 come from the type, so they are fixed once you have a Point<i32, f64>. X2 and Y2 are chosen again at each call. The output is 5 c.
A good rule: put a parameter on the impl when it describes the value the method is called on. Put it on the method when it describes something only that call needs.
Bounds on impl blocks
You can attach trait bounds to the impl itself. Then every method in the block requires them, and the methods are available only when the type meets them.
use std::fmt::Display;
struct Pair<T> {
a: T,
b: T,
}
impl<T> Pair<T> {
fn new(a: T, b: T) -> Self {
Pair { a, b }
}
}
impl<T: Display + PartialOrd> Pair<T> {
fn print_largest(&self) {
if self.a >= self.b {
println!("largest is a = {}", self.a);
} else {
println!("largest is b = {}", self.b);
}
}
}
struct Opaque;
fn main() {
Pair::new(3, 8).print_largest();
Pair::new("pear", "apple").print_largest();
let _unusable = Pair::new(Opaque, Opaque);
}Pair::new works for every type, including Opaque, which implements nothing. print_largest requires Display and PartialOrd. If you added _unusable.print_largest(), the compiler would say the method exists but its trait bounds were not satisfied. That is the message to look for when a method seems to be missing.
This design has a practical benefit. You can build and store a Pair<Opaque> without constraints, and you only pay for the bounds in the methods that need them. Bounding the struct definition itself (struct Pair<T: Display>) is rarely wise, because it forces the bound on every impl block and every function that mentions the type.
Which block applies?
The compiler decides method availability per concrete type, by checking each impl block against it.
Overlap and the duplicate method error
You cannot define the same method name in two blocks that could apply to the same type. Suppose impl<T> Point<T> defines x, and impl Point<f64> also defines x. A Point<f64> would match both. The compiler rejects this with error E0592, "duplicate definitions with name x". Rust has no specialization on stable, so a more specific block cannot override a general one.
There are two ways around this.
- Give the specialized method a different name, as
distance_from_origindoes above. - Move the behavior into a trait and implement the trait separately for each type you need.
The same rule applies across inherent impls and trait impls. Two impls of the same trait for overlapping types conflict, even if you never call the method on a type in the overlap.
Implementing traits for generic types
Trait impls use the same syntax. Declare parameters after impl, then apply them to both the trait and the type.
use std::fmt;
struct Point<T> {
x: T,
y: T,
}
impl<T: fmt::Display> fmt::Display for Point<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
fn main() {
println!("{}", Point { x: 1, y: 2 });
println!("{}", Point { x: 1.5, y: 2.5 });
}The bound T: fmt::Display here is conditional. Point<T> implements Display only when T does. The standard library uses this heavily. For example, Vec<T> implements Clone only when T: Clone.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| "cannot find type `T` in this scope" | Wrote `impl Point<T>` without declaring `T` | Write `impl<T> Point<T>` |
| "method exists but its trait bounds were not satisfied" | The type does not meet the bounds on the block holding the method | Implement the traits, or call the method on a different type |
| E0592 duplicate definitions | A generic block and a specialized block define the same name | Rename one, or use a trait |
| "no method named ... found" on `Point<i32>` | The method lives in `impl Point<f64>` | Use the right type, or add a block for it |
| Unused parameter error on a struct or impl | A declared parameter appears nowhere in the type | Use it, remove it, or see `PhantomData` in a later chapter |
Choosing between the forms
Use a plain impl<T> for behavior that does not depend on what T can do, such as constructors and accessors. Use a bounded impl<T: Bound> when methods need a capability, and group them by the capability they need. Use impl Type<Concrete> when the method makes sense only for one type, as with numeric operations that need f64. If you find yourself writing many specialized blocks that do the same thing, a trait is usually the better tool.
Exercise
Given struct Wrapper<T>(T);, write an impl block that gives Wrapper<T> a method show(&self) -> String returning the inner value formatted with {:?}, but only when T implements Debug. Then say what happens if you call show on a Wrapper holding a type that does not implement Debug.
Show answer
impl<T: std::fmt::Debug> Wrapper<T> { fn show(&self) -> String { format!("{:?}", self.0) } }. Calling show on a Wrapper<Opaque> where Opaque lacks Debug fails at compile time with "method exists but its trait bounds were not satisfied". Constructing the Wrapper itself still works, because the struct has no bound.
Exercise
A Point<T> has impl<T> Point<T> { fn label(&self) -> &str { "point" } }. You add impl Point<i32> { fn label(&self) -> &str { "integer point" } } to override it for integers. Will this compile, and why?
Show answer
No. A Point<i32> matches both blocks, so the compiler reports E0592, duplicate definitions with name label. Stable Rust has no specialization that lets the narrower block override the broader one. Rename the second method or move the behavior into a trait.