Overload struct operators
Reserved inherent method names define operators for a struct. For example, binary + calls add(self, other), while unary - calls neg(self).
Comparison overloads and not return bool. Compound assignment uses the same overloaded binary operation before storing the result.
struct Point { x: int, y: int }
impl Point {
fn add(self: Point, other: Point) -> Point {
Point { x: self.x + other.x, y: self.y + other.y }
}
}
fn main() {
let point = Point { x: 1, y: 2 } + Point { x: 4, y: 5 }
println("${point.x},${point.y}")
}
Examples use the moon toolchain version shown beside each result.
Output & diagnostics
Expected: 5,7
Ctrl/⌘+Enter runs the current lesson.