Sub topic 3
Choosing the Output type
This chapter assumes you can write a trait impl, you know what an associated type is, and you have seen T: Trait bounds. You should also have implemented Add once, as in the previous chapter. Here the focus is the line type Output = ... and what it controls.
What Output means
The Add trait looks like this:
pub trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}Output is an associated type. The compiler computes the type of a + b as <A as Add<B>>::Output, where A and B are the types of the operands. So Output is the result type of the operator expression. It does not have to equal either operand type.
Most impls set Output = Self, which is why the first examples look like a formality. The Standard Library shows how often that is not the case:
| Expression | Output |
|---|---|
| `i32 + i32` | `i32` |
| `&i32 + &i32` | `i32` |
| `String + &str` | `String` |
| `Instant + Duration` | `Instant` |
| `Instant - Instant` | `Duration` |
Subtracting two instants gives a length of time, not an instant. Adding two points in space is meaningless, but subtracting them gives a displacement. Output lets the type system express that.
Why an associated type, not a type parameter
Rhs is a type parameter and Output is an associated type. This follows from one rule: a type can implement Add<Rhs> for many different Rhs types, but for each (Self, Rhs) pair there is exactly one impl, and so exactly one Output.
That rule keeps inference simple. Given the operand types, the result type is determined, so you never annotate it. If Output were a third type parameter, a + b could be ambiguous and the compiler would ask you to pick one.
The rule has a practical consequence. Vector * f64 and Vector * Vector are different impls (different Rhs), so each can have a different Output. Two impls with the same Self and Rhs but different outputs are rejected as conflicting.
An Output that differs from Self
Here is a Point and Vector pair modeled on the Instant and Duration relationship.
use std::ops::{Add, Mul, Sub};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: f64,
y: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vector {
dx: f64,
dy: f64,
}
// Point - Point = Vector
impl Sub for Point {
type Output = Vector;
fn sub(self, rhs: Point) -> Vector {
Vector { dx: self.x - rhs.x, dy: self.y - rhs.y }
}
}
// Point + Vector = Point
impl Add<Vector> for Point {
type Output = Point;
fn add(self, v: Vector) -> Point {
Point { x: self.x + v.dx, y: self.y + v.dy }
}
}
// Vector * f64 = Vector (scaling)
impl Mul<f64> for Vector {
type Output = Vector;
fn mul(self, k: f64) -> Vector {
Vector { dx: self.dx * k, dy: self.dy * k }
}
}
// Vector * Vector = f64 (dot product)
impl Mul<Vector> for Vector {
type Output = f64;
fn mul(self, rhs: Vector) -> f64 {
self.dx * rhs.dx + self.dy * rhs.dy
}
}
fn main() {
let a = Point { x: 1.0, y: 1.0 };
let b = Point { x: 4.0, y: 5.0 };
let v = b - a;
assert_eq!(v, Vector { dx: 3.0, dy: 4.0 });
assert_eq!(a + v, b);
assert_eq!(v * 2.0, Vector { dx: 6.0, dy: 8.0 });
assert_eq!(v * v, 25.0);
}Point + Point is not defined, so it does not compile. The type system rejects a meaningless operation instead of letting it through.
The diagram shows how the compiler types a + (b - a). The Output of the first impl becomes an operand of the second.
Self::Output in the method signature
Inside an impl, you can write the return type as Vector or as Self::Output. Both are the same type. Self::Output has one advantage: if you later change the associated type, the signature follows. The concrete name reads more clearly in short impls. Pick one style and use it throughout a codebase.
The compiler checks that the body returns the declared Output. If you write type Output = Vector but the body builds a Point, you get an ordinary type mismatch.
Output computed from generic parameters
When your type is generic, Output can depend on the element type's own Output. That avoids forcing T: Add<Output = T>.
use std::ops::Add;
#[derive(Debug, PartialEq)]
struct Pair<T>(T, T);
impl<T: Add> Add for Pair<T> {
type Output = Pair<T::Output>;
fn add(self, rhs: Pair<T>) -> Self::Output {
Pair(self.0 + rhs.0, self.1 + rhs.1)
}
}
fn main() {
assert_eq!(Pair(1, 2) + Pair(3, 4), Pair(4, 6));
assert_eq!(Pair(0.5, 1.5) + Pair(0.5, 0.5), Pair(1.0, 2.0));
}This impl works for any T that can be added, even if adding two T values yields a different type. It is more general than the Output = T version. The cost is that the type Pair<T::Output> can look less obvious in error messages.
Output in generic code
When you write a function over T: Add, the result type is T::Output unless you constrain it.
use std::ops::{Add, Sub};
use std::time::{Duration, Instant};
fn gap<T: Sub>(later: T, earlier: T) -> T::Output {
later - earlier
}
fn sum3<T>(a: T, b: T, c: T) -> T
where
T: Add<Output = T>,
{
a + b + c
}
fn main() {
assert_eq!(gap(10, 4), 6);
let start = Instant::now();
let end = start + Duration::from_secs(2);
let d: Duration = gap(end, start);
assert_eq!(d, Duration::from_secs(2));
assert_eq!(sum3(1, 2, 3), 6);
}The two bounds do different jobs.
T: SubleavesOutputopen.gapworks forInstant, where the result is aDuration, as well as for integers.T: Add<Output = T>pinsOutputtoT. That is what makesa + b + ccompile. The first+producesT, which is a valid left operand for the second+. With onlyT: Add, the intermediate value would beT::Output, and the compiler would not know it can be added again.
Choosing an Output: a checklist
Use these questions when you write an impl.
- What does the operation mean for the domain? Offset between positions is a displacement, not a position. Use a separate type.
- Can the result be closed under the operation? If the result is the same type as the operands (
Vector + Vector), useOutput = Self. Chaining then works with no extra bounds. - Will users chain the result? If
Outputis a different type, make sure the next operator they are likely to apply is also implemented for it. - Is the result surprising?
Vector * Vector -> f64is legal. Many readers would expect aVectoror a cross product, so a named method such asdotis often clearer.
A few things to avoid:
- Do not make
OutputaResultorOptionto report overflow or invalid input. Operators read as total operations, and every consumer must then unwrap the result. Providechecked_addinstead, as the integer types do. - Do not use
Output = ()or other unrelated types as a trick for side effects. Use a compound assignment trait or a method.
Common errors
- "cannot add
PointtoPoint": noAdd<Point> for Pointimpl exists. Either add one, or check whether the operation should exist at all. - "conflicting implementations": you wrote two impls with the same
SelfandRhsbut differentOutput. Only one impl per pair is allowed. Differentiate them byRhs, or use a named method for the second meaning. - "expected
T, found associated type": a generic function returnsa + basTbut only hasT: Add. AddOutput = Tto the bound, or change the return type toT::Output. - Inference failure on literals:
Pair(1, 2) + Pair(3, 4)works because integer literals default toi32. With more complicatedRhsimpls, annotate a literal (2.0_f64) if several impls could apply.
Exercise
A Money(i64) type represents cents. You want Money + Money to give Money, and Money / Money to give the ratio as an f64. Write the Div impl, including the correct Output. Why does the compiler accept both impls even though both are on Money?
Show answer
Use impl Div for Money { type Output = f64; fn div(self, rhs: Money) -> f64 { self.0 as f64 / rhs.0 as f64 } }. The Add and Div impls are for two different traits, so each trait has its own Output and neither conflicts with the other. Within one trait, an impl is identified by Self and Rhs, and Div<Money> for Money has exactly one Output, which is f64.
Exercise
What bound does fn total<T>(xs: &[T]) -> T need so that the body xs.iter().copied().fold(first, |acc, x| acc + x) compiles, where first is a T? Explain why T: Add is not enough.
Show answer
It needs T: Copy + Add<Output = T>. The closure must return the same type as the accumulator acc, which is T. With only T: Add, acc + x has type T::Output, which the compiler cannot assume equals T, so it reports a type mismatch. Copy is needed for copied() and so the values can be passed by value to +.