Sub topic 14
Default Type Parameters
This chapter assumes you can declare generic structs and traits, write impl<T> blocks, and read trait bounds. You should also know that a + b calls the Add trait. A default type parameter lets a generic item pick a type for you when the caller doesn't name one.
What a default type parameter is
A type parameter can carry a default with =:
struct Pair<A, B = A> {
first: A,
second: B,
}When someone writes Pair<i32>, the compiler fills in the missing argument and reads it as Pair<i32, i32>. Callers who need two different types still write Pair<i32, &str>.
The default is a convenience for the common case. It does not limit what the parameter can be.
struct Pair<A, B = A> {
first: A,
second: B,
}
fn main() {
let same: Pair<i32> = Pair { first: 1, second: 2 };
let mixed: Pair<i32, &str> = Pair { first: 1, second: "two" };
println!("{} {}", same.first, same.second);
println!("{} {}", mixed.first, mixed.second);
}Here B = A refers to an earlier parameter. A default may use any parameter declared before it.
The standard library example: `Add<Rhs = Self>`
The best-known default is in std::ops::Add:
trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}Rhs is the type of the right-hand operand. Most of the time you add two values of the same type, so Rhs defaults to Self. Writing impl Add for Point therefore means impl Add<Point> for Point.
You override the default when the two operands differ:
use std::ops::Add;
#[derive(Debug, Clone, Copy)]
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,
}
}
}
#[derive(Debug, Clone, Copy)]
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 d = Millimeters(500) + Meters(2);
println!("{d:?}");
}This prints Point { x: 4, y: 6 } and then Millimeters(2500).
Why `Rhs` is a parameter and `Output` is not
Add uses both a type parameter and an associated type, and the choice is deliberate.
Rhsis a type parameter because one type can implementAddseveral times.Millimeterscan addMeters, and it could also addMillimeters. Each is a different trait,Add<Meters>orAdd<Millimeters>.Outputis an associated type because, onceSelfandRhsare known, there is exactly one result type.
Use a parameter when several implementations per type make sense. Use an associated type when there is one answer per implementation. Defaults are available only on parameters. Defaults for associated types are still unstable.
Defaults on your own traits
Your own traits can use the same pattern. Here the default target type is String:
trait Convert<Target = String> {
fn convert(&self) -> Target;
}
struct Celsius(f64);
impl Convert for Celsius {
fn convert(&self) -> String {
format!("{:.1} C", self.0)
}
}
impl Convert<f64> for Celsius {
fn convert(&self) -> f64 {
self.0 * 9.0 / 5.0 + 32.0
}
}
fn main() {
let c = Celsius(21.5);
let text = <Celsius as Convert>::convert(&c);
let fahrenheit = <Celsius as Convert<f64>>::convert(&c);
println!("{text} = {fahrenheit:.1} F");
}Inside the qualified path <Celsius as Convert>, the omitted argument is String. Without the qualified path, a call such as c.convert() is ambiguous unless the surrounding code fixes the result type.
Where defaults are allowed
| Item | Defaults allowed |
|---|---|
| `struct`, `enum` | Yes |
| `trait` | Yes, and only traits may use `Self` in a default |
| `type` alias | Yes |
| `fn` | No |
| `impl` block | No |
The compiler rejects defaults on functions and impl blocks. Those positions are inferred from the arguments or from the type being implemented, so a default has nothing to do there.
Declaration order matters. Lifetimes come first, then types and const parameters. Once one type parameter has a default, every type parameter after it must also have one. This is wrong:
struct Bad<A = i32, B> {
a: A,
b: B,
}The compiler reports that generic parameters with a default must be trailing. The reason is that a caller supplies arguments from the left. If A could be skipped while B was required, Bad<u8> would be ambiguous.
Const parameters can have defaults too
Const generics follow the same rule. This buffer holds four slots unless the caller asks for more:
struct Buf<T, const N: usize = 4> {
items: [Option<T>; N],
}
impl<T: Copy, const N: usize> Buf<T, N> {
fn new() -> Self {
Buf { items: [None; N] }
}
fn capacity(&self) -> usize {
self.items.len()
}
}
fn main() {
let small: Buf<u8> = Buf::new();
let large: Buf<u8, 16> = Buf::new();
println!("{} {}", small.capacity(), large.capacity());
}This prints 4 16.
A default that real code relies on: `HashMap`
HashMap is declared as HashMap<K, V, S = RandomState>. The third parameter is the hasher builder. You rarely write it, because the default supplies the standard hasher. When you want a different one, you name it:
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
fn main() {
let mut a: HashMap<&str, i32> = HashMap::new();
a.insert("a", 1);
let mut b: HashMap<&str, i32, BuildHasherDefault<DefaultHasher>> = HashMap::default();
b.insert("b", 2);
println!("{} {}", a.len(), b.len());
}The two maps have different types, because their third arguments differ. HashMap::new exists only for the RandomState version. A map with a custom hasher is built with default() or with_hasher. This is a common design: the defaulted parameter keeps the everyday path short, and the specialized path is available through other constructors.
Defaults are not used for inference
This is the most common surprise. A default applies only when a type is written out and an argument is omitted. It is never a fallback for type inference.
- In
let p: Pair<i32> = ..., the type is written, soBbecomesi32. - In
let p = Pair { first: 1, second: "x" };, nothing is written. The compiler infersB = &strfrom the value. The defaultB = Aplays no part. - If nothing constrains a parameter, the compiler reports "type annotations needed", even when the parameter has a default.
Design guidance
Add a default when one choice is right for most users and the other choices are rare but legitimate. Add<Rhs = Self> and HashMap's hasher both fit.
Weigh these points before adding one to a public type:
- A default lets you add a parameter to an existing type without rewriting every written use of that type. Plain mentions like
Wrapperstill compile. - It can still break callers. Code that relied on inference may now see an extra parameter that it needs to constrain, and code that implements your trait may behave differently.
- A defaulted parameter hides a choice. If the wrong default would silently cause bugs, make callers state the type.
- Prefer a separate type alias, such as
type Meters = Length<MetersUnit>, when you want a named shortcut and not a hidden default.
Exercise
A teammate writes struct Cache<K = String, V> { key: K, value: V }. Why does this fail to compile, and what are two ways to fix it?
Show answer
A parameter without a default (V) follows a parameter with a default (K). Defaulted parameters must be trailing. Fix it by reordering to Cache<V, K = String>, or by giving V a default as well, for example Cache<K = String, V = i32>.
Exercise
Given struct Pair<A, B = A> { first: A, second: B }, what are the types of x and y in let x: Pair<u8> = Pair { first: 1, second: 2 }; and let y = Pair { first: 1u8, second: "s" };? Does the default matter for y?
Show answer
x is Pair<u8, u8>, because the omitted B takes the default A = u8. y is Pair<u8, &str>, because the compiler infers B from the value. The default does not matter for y, since defaults are not used for inference.
Exercise
Why does Add take Rhs as a defaulted type parameter but Output as an associated type?
Show answer
One type may need several Add implementations with different right-hand types, so Rhs must be a parameter, and Self is the sensible default. For a given Self and Rhs there is only one result, so Output is an associated type fixed by each implementation.