Operator overloading in Rust
Operators are traits: implement Add and + works on your type.
use std::ops::{Add, AddAssign};
#[derive(Debug, Clone, Copy)]
struct Vec2 {
x: f64,
y: f64,
}
impl Add for Vec2 {
type Output = Vec2;
fn add(self, other: Vec2) -> Vec2 {
Vec2 { x: self.x + other.x, y: self.y + other.y }
}
}
impl AddAssign for Vec2 {
fn add_assign(&mut self, other: Vec2) {
self.x += other.x;
self.y += other.y;
}
}
fn main() {
let a = Vec2 { x: 1.0, y: 2.0 };
let b = Vec2 { x: 0.5, y: 0.5 };
println!("{:?}", a + b);
let mut total = a;
total += b;
println!("{:?}", total);
}
How it works
std::ops::Addhas anOutputassociated type.AddAssigngives you the+=form.- Only implement an operator when the meaning is obvious.
Keywords and builtins used here
OutputVec2addadd_assignf64fnforimplletmainmutselfstructtypeuse
The run, in numbers
- Lines
- 32
- Characters to type
- 498
- Tokens
- 175
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 100 seconds.
Step 1 of 4 in Operators & access, step 12 of 19 in Traits & generics.