Sub topic 14
Default type parameters
This chapter assumes you can write generic structs and traits, implement a trait for a type, and read trait bounds. A default type parameter gives a generic parameter a fallback type, so callers can leave it out.
The syntax
You write the default after the parameter name with =:
struct Wrapper<T = i32> {
value: T,
}When you name Wrapper without type arguments in a type position, the compiler reads it as Wrapper<i32>.
struct Wrapper<T = i32> {
value: T,
}
impl<T> Wrapper<T> {
fn new(value: T) -> Self {
Wrapper { value }
}
fn get(&self) -> &T {
&self.value
}
}
fn main() {
let a: Wrapper = Wrapper::new(5);
let b: Wrapper<&str> = Wrapper::new("hi");
let c = Wrapper::new(7u8);
println!("{} {} {}", a.get(), b.get(), c.get());
}Here a has type Wrapper<i32> because the annotation Wrapper expands to its default. Variable b overrides the default. Variable c has no annotation, so T is inferred as u8.
The main use: Rhs = Self
The standard library uses defaults most often in operator traits. Add is declared roughly like this:
trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}Most types add to their own kind, so impl Add for Point means impl Add<Point> for Point. When you want to add a different type, you name Rhs explicitly.
use std::ops::Add;
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point { x: self.x + other.x, y: self.y + other.y }
}
}
struct Millimeters(u32);
struct Meters(u32);
impl Add<Meters> for Millimeters {
type Output = Millimeters;
fn add(self, other: Meters) -> Millimeters {
Millimeters(self.0 + other.0 * 1000)
}
}
fn main() {
let p = Point { x: 1, y: 2 } + Point { x: 3, y: 4 };
println!("{:?}", p);
let total = Millimeters(500) + Meters(2);
println!("{}", total.0);
}The first impl uses the default. The second overrides it. Both are valid because Add<Point> and Add<Meters> are different traits.
Rules and gotchas
- Order: Parameters with defaults must come after parameters without them.
struct Pair<T = i32, U>is an error. - Where defaults apply: They work on structs, enums, traits, and type aliases. They do not work on
implheaders or functions. In animpl, you writeimpl<T> Wrapper<T>, notimpl<T = i32> Wrapper<T>. - No fallback during inference: The default is used when you write the bare type name in a type position. It is not a fallback when inference has nothing to go on.
Wrapper::new(7u8)givesWrapper<u8>, notWrapper<i32>. An expression whose type is truly undetermined still fails with "type annotations needed". - Compatibility: Adding a default to an existing parameter is backward compatible. This is why
HashMap<K, V, S = RandomState>could gain its hasher parameter without breaking code that wroteHashMap<K, V>.
| Situation | Default used? |
|---|---|
| `let a: Wrapper = ...` | Yes |
| `Wrapper<&str>` | No, you supplied the type |
| `Wrapper::new(7u8)` | No, inference picks `u8` |
| `fn f<T = i32>()` | Not allowed |
When to use them
Add a default when one type is right for nearly every caller and you still want to allow others. Examples are the right-hand side of an operator, or an allocator or hasher parameter. Do not use a default only to save typing. A default can hide that a type is generic, and it can make error messages harder to read.
Exercise
Why does let w = Wrapper::new(2.5); produce Wrapper<f64> instead of Wrapper<i32>, even though Wrapper<T = i32>?
Show answer
The default applies only when the type is written without arguments in a type position, such as let w: Wrapper. Here the compiler infers T from the argument 2.5, and inference does not fall back to the default.