Sub topic 6
Generic impl blocks and specialized impls
This chapter assumes you can define a generic struct like Point<T>, write a trait bound, and read an impl block. It covers how impl blocks interact with type parameters, and how that lets you give some instantiations of a type extra methods.
Declaring the parameter on impl
A method block for a generic type must declare the type parameter after the impl keyword:
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);
println!("{}", p.x());
}There are two uses of T here. The first, in impl<T>, declares it. The second, in Point<T>, uses it. Without the declaration, Rust reads T as a concrete type named T and reports that it cannot find it.
Every Point<_> gets new and x, whatever the element type.
Specialized impls
If you write a concrete type in the angle brackets of the type, and declare no parameter after impl, the block applies only to 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());
}distance_from_origin exists only on Point<f64>. Calling it on q, a Point<i32>, fails at compile time with error E0599 (no method found). The compiler notes that the method exists for Point<f64>.
Bounded impls
Between "all types" and "one exact type" sits a bound on the parameter. The block then applies to every T that meets the bound:
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 show_largest(&self) {
if self.a >= self.b {
println!("largest is {}", self.a);
} else {
println!("largest is {}", self.b);
}
}
}
fn main() {
Pair::new(3, 7).show_largest();
Pair::new("pear", "apple").show_largest();
}Pair<T> can be built for any T. show_largest appears only when T implements both Display and PartialOrd. A Pair<Vec<i32>> is valid, but calling show_largest on it is an error, because Vec<i32> does not implement Display.
This pattern is common in the standard library. For example, Vec<T> has methods like dedup that are only available when T: PartialEq.
Common errors
- Forgetting
<T>afterimpl. The compiler reports an unknown typeT. - Putting a bound on the struct definition when only some methods need it. A bound on the struct forces it on every use of the type, so it is usually better to bound the
implblock. - Defining the same method name in two overlapping inherent blocks, such as
impl<T> Point<T>andimpl Point<f64>. This is error E0592 (duplicate definitions). Specialized blocks must add methods, not replace them.
Exercise
You have struct Wrapper<T>(T);. You want a len_doubled method that exists only when T is String. Which impl header do you write, and what happens if you call it on Wrapper<i32>?
Show answer
Write impl Wrapper<String> { fn len_doubled(&self) -> usize { self.0.len() * 2 } }. No <T> follows impl, because the block names a concrete type. Calling it on Wrapper<i32> is a compile-time error (E0599, no method found).