Sub topic 2
Mixed Operand Types and Reference Operators
Assume you know Rust structs, traits, generics, ownership, borrowing, and associated types. Operator overloading connects familiar symbols to trait methods in std::ops.
Mixed operand types with `Rhs`
Binary operator traits have an Rhs type parameter, meaning “right-hand side.” It defaults to Self, so Add normally combines two values of the same type. Set it explicitly for mixed operands.
use std::ops::{Add, Mul};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
impl Mul<f64> for Vec2 {
type Output = Vec2;
fn mul(self, factor: f64) -> Vec2 {
Vec2 {
x: self.x * factor,
y: self.y * factor,
}
}
}
impl Mul<Vec2> for f64 {
type Output = Vec2;
fn mul(self, vector: Vec2) -> Vec2 {
vector * self
}
}
fn main() {
let vector = Vec2 { x: 2.0, y: 3.0 };
assert_eq!(vector * 2.0, Vec2 { x: 4.0, y: 6.0 });
assert_eq!(2.0 * vector, vector * 2.0);
}The Output associated type can differ from both operands. The compiler maps a * b to Mul::mul(a, b).
Compound assignment
+=, -=, and similar operators use separate traits such as AddAssign. These methods borrow the left operand mutably and return ().
use std::ops::AddAssign;
impl AddAssign for Vec2 {
fn add_assign(&mut self, other: Vec2) {
self.x += other.x;
self.y += other.y;
}
}Implement compound assignment when mutation is a natural, efficient form of the operation.
Unary operators
-value calls Neg::neg, while !value calls Not::not. These traits usually consume the operand and return an Output value. Implement them only when the meaning is obvious.
Operators for references
For non-Copy types, implement an operator for references to avoid moving or cloning values:
impl Add<&Vec2> for &Vec2 {
type Output = Vec2;
fn add(self, other: &Vec2) -> Vec2 {
Vec2 { x: self.x + other.x, y: self.y + other.y }
}
}The expression &a + &b then borrows both operands and creates a new result.
> callout note > Operator implementations are chosen by the exact operand types. Vec2 + Vec2, &Vec2 + &Vec2, and Vec2 * f64 may require separate implementations.
Exercise
Why does Mul<f64> for Vec2 use f64 in angle brackets?
Show answer
It sets the Rhs type, declaring that the right operand is an f64 rather than another Vec2.