Sub topic 5
Mixed operand types with the Rhs parameter
This chapter assumes you can write an impl Add for a struct, you know what the Output associated type does, and you understand why Copy matters when operands are passed by value.
Rhs is a type parameter
The binary operator traits take a type parameter for the right-hand operand. Add is declared roughly like this:
trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}Rhs stands for "right-hand side". The default = Self is why impl Add for Vec2 means impl Add<Vec2> for Vec2. To accept a different right-hand type, name it in the impl.
Multiplying a vector by a scalar
Scaling a vector takes a Vec2 on the left and an f64 on the right:
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);
}The expression v * 2.0 becomes Mul::<f64>::mul(v, 2.0). The compiler picks the impl from the types of both operands.
Output is a separate choice from Rhs. Here both impls return Vec2, but nothing forces that. A dot product could be impl Mul<Vec2> for Vec2 with Output = f64.
Several impls on one type
A type can implement the same operator trait many times, as long as each Rhs differs. The impls in the table below can all exist side by side.
| Expression | Impl | Output |
|---|---|---|
| `v * 2.0` | `impl Mul<f64> for Vec2` | `Vec2` |
| `2.0 * v` | `impl Mul<Vec2> for f64` | `Vec2` |
| `v * w` | `impl Mul<Vec2> for Vec2` | `Vec2` or `f64`, your choice |
Making operands commute
Rust does not assume a * b equals b * a. The impl for Vec2 * f64 says nothing about f64 * Vec2, so you write the second impl yourself. The usual pattern is to have the reversed impl call the first one, as v * self does above.
You are allowed to implement Mul<Vec2> for f64 even though Mul and f64 both come from the standard library. The orphan rule requires a local type somewhere in the impl, and Vec2 appears as the trait's type argument. A later chapter covers the rule in full.
Common errors
Other mistakes you are likely to hit:
- Implementing only
Mul<f64> for Vec2and then writing2.0 * v. The error saysf64cannot be multiplied byVec2. - Adding a second impl and breaking type inference. If
Vec2has bothMul<f64>andMul<f32>, an unsuffixed float literal likev * 2.0may become ambiguous. Annotate the literal, for example2.0_f64. - Forgetting
Copy. WithVec2notCopy,v * 2.0movesv, and the next use ofvfails to compile.
Exercise
You have impl Mul<f64> for Vec2 with type Output = Vec2. The expression 3.0 * v does not compile. Write the impl that fixes it, and say why the compiler accepts it even though f64 is a foreign type.
Show answer
impl Mul<Vec2> for f64 { type Output = Vec2; fn mul(self, v: Vec2) -> Vec2 { v * self } }. The orphan rule is satisfied because the local type Vec2 appears as the trait's type argument, so the impl is not made entirely of foreign pieces.