Sub topic 5
Mixed operand types with the Rhs parameter
This chapter assumes you can write a basic impl Add for T, know that Output is an associated type, and understand that operators take their operands by value (covered in the previous chapters). It uses generics and trait parameters, but nothing beyond that.
The Rhs parameter in the trait definition
Every binary operator trait in std::ops has the same shape. Here is Add, simplified:
pub trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}Rhs stands for "right-hand side". It is a type parameter with a default of Self. When you write impl Add for Vec2, the compiler reads it as impl Add<Vec2> for Vec2, so both operands are Vec2.
To mix operand types, name the Rhs explicitly: impl Mul<f64> for Vec2 means "a Vec2 on the left and an f64 on the right".
The same default applies to Sub, Mul, Div, Rem, the bitwise traits, and the shift traits. The compound assignment traits such as AddAssign also take Rhs, which a later chapter covers.
Scaling a vector with Mul<f64>
A vector times a scalar is the standard example. The left operand is a Vec2, the right operand is an f64, and the result is a Vec2.
use std::ops::Mul;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
impl Mul<f64> for Vec2 {
type Output = Vec2;
fn mul(self, k: f64) -> Vec2 {
Vec2 { x: self.x * k, y: self.y * k }
}
}
fn main() {
let v = Vec2 { x: 1.0, y: 2.0 };
assert_eq!(v * 2.0, Vec2 { x: 2.0, y: 4.0 });
}The Rhs type appears in two places that must agree. It appears in the trait argument, Mul<f64>, and in the method signature, k: f64. The compiler rejects the impl if they differ.
Making the operands commute
The impl above handles v * 2.0. It does not handle 2.0 * v. That expression has an f64 on the left, so the compiler looks for impl Mul<Vec2> for f64. Mathematically the two orders are the same, but Rust does not infer that. You write the second impl yourself.
use std::ops::Mul;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
impl Mul<f64> for Vec2 {
type Output = Vec2;
fn mul(self, k: f64) -> Vec2 {
Vec2 { x: self.x * k, y: self.y * k }
}
}
impl Mul<Vec2> for f64 {
type Output = Vec2;
fn mul(self, v: Vec2) -> Vec2 {
v * self
}
}
fn main() {
let v = Vec2 { x: 1.0, y: 2.0 };
assert_eq!(v * 2.0, Vec2 { x: 2.0, y: 4.0 });
assert_eq!(2.0 * v, v * 2.0);
}Two points about the second impl:
- It is allowed even though
f64andMulboth come from the standard library. The trait argumentVec2is a local type, which satisfies the orphan rule. A later chapter covers the rule in full. - It delegates to the first impl (
v * self), so the arithmetic is written once.
By contrast, impl Mul<f64> for f64 would be rejected. The standard library already provides it, and none of the types involved is local.
One type, several Rhs types, different Outputs
A type can implement the same operator trait many times, once per Rhs. Each impl chooses its own Output. This lets you model types where the operators change the kind of value, such as points and displacements:
- A
Pointplus aVec2displacement is aPoint. - A
Pointminus aPointis aVec2. - A
Pointminus aVec2is aPoint.
use std::ops::{Add, Sub};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: f64,
y: f64,
}
impl Add<Vec2> for Point {
type Output = Point;
fn add(self, d: Vec2) -> Point {
Point { x: self.x + d.x, y: self.y + d.y }
}
}
impl Sub<Vec2> for Point {
type Output = Point;
fn sub(self, d: Vec2) -> Point {
Point { x: self.x - d.x, y: self.y - d.y }
}
}
impl Sub for Point {
type Output = Vec2;
fn sub(self, other: Point) -> Vec2 {
Vec2 { x: self.x - other.x, y: self.y - other.y }
}
}
fn main() {
let p = Point { x: 1.0, y: 1.0 };
let q = Point { x: 4.0, y: 5.0 };
let d = Vec2 { x: 3.0, y: 4.0 };
assert_eq!(q - p, d);
assert_eq!(p + d, q);
assert_eq!(q - d, p);
assert_eq!(<Point as Add<Vec2>>::add(p, d), p + d);
}There is deliberately no Add<Point> for Point. Adding two positions has no geometric meaning, so the compiler reports an error if someone writes p + q. The type system now catches that mistake.
The standard library uses the same design for time. Instant + Duration is an Instant, and Instant - Instant is a Duration. String + &str is a String, and String + String does not compile.
The last assertion shows the explicit form, <Point as Add<Vec2>>::add(p, d). You need the as Add<Vec2> part because Point has more than one Add impl. If it had only one, Add::add(p, d) would be enough.
How the compiler picks an impl
For a OP b, the compiler looks at the type of a and the type of b. It then searches for an impl of the operator trait for the left type with the right type as Rhs. The impl it finds supplies the Output.
This explains why Rhs is a type parameter and Output is an associated type:
Rhsis an input. A type may have several impls of the trait, one for eachRhs. The compiler chooses between them using the right operand's type.Outputis determined by the inputs. OnceSelfandRhsare fixed, there is exactly oneOutput. An associated type enforces that, because a type cannot have two impls of the same trait for the sameRhs.
Literals and inference
Operand types must match an impl exactly. Rust does not convert between numeric types for you, so v * 2 fails. The literal 2 is an integer, and no Mul<{integer}> impl exists for Vec2. Write 2.0, or add an impl for the integer type.
use std::ops::Mul;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
impl Mul<f64> for Vec2 {
type Output = Vec2;
fn mul(self, k: f64) -> Vec2 {
Vec2 { x: self.x * k, y: self.y * k }
}
}
impl Mul<i32> for Vec2 {
type Output = Vec2;
fn mul(self, k: i32) -> Vec2 {
self * f64::from(k)
}
}
fn main() {
let v = Vec2 { x: 1.0, y: 2.0 };
let n: i32 = 3;
assert_eq!(v * 2.0, Vec2 { x: 2.0, y: 4.0 });
assert_eq!(v * n, Vec2 { x: 3.0, y: 6.0 });
}Adding impls for many scalar types by hand gets repetitive. The macro chapter later in this tutorial shows how to generate them. Avoid a single blanket impl such as impl<T: Into<f64>> Mul<T> for Vec2. It can overlap with other impls on the same type and produce coherence errors.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `2.0 * v` fails but `v * 2.0` works | Only `impl Mul<f64> for Vec2` exists | Add `impl Mul<Vec2> for f64` |
| `v * 2` fails | The literal is an integer and no impl takes one | Write `2.0`, or add `impl Mul<i32> for Vec2` |
| `Add::add(p, d)` is ambiguous | `Point` has several `Add` impls | Use `<Point as Add<Vec2>>::add(p, d)` |
| Conflicting implementations | Two impls with the same `Self` and `Rhs` | Keep one impl for each `Self` and `Rhs` pair |
| `p + q` compiles when it should not | A blanket `Add<Point> for Point` was added | Remove it, so only meaningful combinations exist |
Exercises
Exercise
A type Vec2 has only impl Mul<f64> for Vec2. Why does 3.0 * v fail to compile, and what single impl fixes it without changing the Vec2 impl?
Show answer
The left operand is an f64, so the compiler looks for an impl of Mul<Vec2> for f64, and none exists. Rust does not assume that multiplication commutes. Adding impl Mul<Vec2> for f64 with type Output = Vec2 fixes it. The body can delegate to the existing impl by returning v * self. The impl is allowed because the trait argument Vec2 is a local type.
Exercise
You have Meters(f64) and Seconds(f64) newtypes and a MetersPerSecond(f64) newtype. Which impl makes Meters(100.0) / Seconds(20.0) produce a MetersPerSecond, and why is it a different kind of impl from impl Div for Meters?
Show answer
Use impl Div<Seconds> for Meters with type Output = MetersPerSecond. The Rhs parameter is Seconds, not the default Self, and the Output differs from both operand types. impl Div for Meters would mean Div<Meters> for Meters, which is a ratio of two lengths, so the right operand would have to be Meters. Because Rhs is a trait parameter, one type can have both impls without conflict.