Sub topic 3
Choosing the Output type
This chapter assumes you know traits, associated types, and the Add implementation from the previous chapter. It covers the Output type that every binary operator trait declares and how to choose it.
What Output is
Each binary operator trait in std::ops declares an associated type named Output. The operator expression has this type. For a - b, the compiler looks for Sub on the type of a, and the result type is <A as Sub<B>>::Output.
The trait does not require Output to be Self. It can be any type, and you pick it in the impl.
When Output differs from Self
Subtracting two points does not give a point. It gives the displacement between them. Modelling that with a separate type makes the compiler reject nonsense such as treating a difference as a location.
use std::ops::Sub;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: f64,
y: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Offset {
dx: f64,
dy: f64,
}
impl Sub for Point {
type Output = Offset;
fn sub(self, rhs: Point) -> Offset {
Offset {
dx: self.x - rhs.x,
dy: self.y - rhs.y,
}
}
}
fn main() {
let a = Point { x: 5.0, y: 7.0 };
let b = Point { x: 2.0, y: 3.0 };
let d: Offset = a - b;
assert_eq!(d, Offset { dx: 3.0, dy: 4.0 });
}The signature could also say -> Self::Output. Both spellings are the same type. Writing Self::Output keeps the signature correct if you later change the associated type.
Why it is an associated type
Output is an associated type and not a second type parameter. Given Self and Rhs, the trait allows only one result type. That is why a - b has a single, unambiguous type, and type inference never needs an annotation to choose among results.
The same fact shows up in generic code. To say "adding two T values gives a T", you constrain the associated type with Add<Output = T>. You will use this in the chapter on generic bounds.
Output controls chaining
An expression like a - b - c is (a - b) - c. The first subtraction yields an Offset, so the second needs Sub<Point> implemented for Offset. If it does not exist, the compiler reports that Offset cannot be subtracted by Point. Choosing Output is therefore also choosing which expressions can be written next.
use std::ops::Add;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Offset {
dx: f64,
dy: f64,
}
impl Add for Offset {
type Output = Offset;
fn add(self, rhs: Offset) -> Offset {
Offset { dx: self.dx + rhs.dx, dy: self.dy + rhs.dy }
}
}
fn main() {
let a = Offset { dx: 1.0, dy: 0.0 };
let b = Offset { dx: 0.0, dy: 2.0 };
let c = Offset { dx: 1.0, dy: 1.0 };
// Works because Offset + Offset is Offset, so the chain continues.
assert_eq!(a + b + c, Offset { dx: 2.0, dy: 3.0 });
}When Output = Self, chains always compose. A different Output breaks the chain unless the next operator is also defined.
Choosing Output in practice
- Start with
Selfwhen the operation is closed over the type, as with numbers, vectors, and matrices. - Use a different type when the result has a different meaning, as with point minus point.
- Avoid surprising result types, such as returning a
Stringfrom+on a numeric type.
Exercise
A type Money implements Sub with type Output = Money. A colleague wants price - discount to return a Percent instead. Which line of the impl changes, and what happens to existing code that writes let total: Money = a - b;?
Show answer
Change type Output = Money; to type Output = Percent; and make sub return Percent. The existing line then fails to compile with a type mismatch, because a - b now has type Percent, not Money.