The Rust Add trait defines how a type responds to the + operator. Because Rust cannot guess what combining two values should mean, a custom type must implement Add manually. section 7.1 section 20.3.2
An Add implementation specifies:
- The output type produced by addition through type Output. section 20.3.2
- The add method, which receives the left and right values and returns the combined value. section 20.3.2
- The meaning of the combination, such as adding corresponding fields in a Point or combining population and GDP in a Country. section 7.1 section 20.3.2
Adding two points
A Point implementation sets Output to Self and returns a new Point whose x and y fields are added separately. Afterward, expressions such as point_a + point_b use that behavior. section 20.3.2
use std::ops::Add; #1
#[derive(Debug, Copy, Clone, PartialEq)] #2
struct Point {
x: i32,
y: i32,
}
impl Add for Point {
type Output = Self; #3
fn add(self, other: Self) -> Self {
Self {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
Browse the focused Point implementation showing std::ops::Add, the Output type, and field-by-field addition. section 20.3.2
