liveBook · Manning

Add trait

As explained in Learn Rust in a Month of Lunches

The Rust Add trait defines how a type participates in addition with another value.

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

How Learn Rust in a Month of Lunches covers it

How deep it goes
Works through complete Point and Country implementations but does not descend into operator-resolution internals.
Examples
Uses field-wise Point addition and Country addition that combines names, populations, and GDP values.
What it assumes
Assumes basic structs and traits while teaching why operator behavior must be specified manually.
What you can do after
Build it from scratch by implementing Add for a custom Rust type and using + with its values.
How it connects
Connects Add with traits, operator overloading, associated types, and related traits such as Sub, Mul, Div, and AddAssign.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.