std::ops traits — overload operators.
Add:
1use std::ops::Add;23struct Point { x: f64, y: f64 }45impl Add for Point {6 type Output = Point;78 fn add(self, other: Point) -> Point {9 Point {10 x: self.x + other.x,11 y: self.y + other.y,12 }13 }14}1516let p1 = Point { x: 1.0, y: 2.0 };17let p2 = Point { x: 3.0, y: 4.0 };18let p3 = p1 + p2;
Index:
1use std::ops::Index;23struct Matrix {4 data: Vec<Vec<f64>>,5}67impl Index<usize> for Matrix {8 type Output = Vec<f64>;910 fn index(&self, row: usize) -> &Vec<f64> {11 &self.data[row]12 }13}
Key: Implement std::ops traits for operators.