Add in Rust

In Rust, the add method is a crucial part of the Add trait, which is used to define how two instances of a type can be combined using the + operator. This trait is implemented by defining the add function, which takes two instances of a type and returns the result of their addition. The Add trait is located within the std::ops module, which contains all the traits used for various operations, such as Sub for subtraction, Mul for multiplication, and so on.

Implementing the Add Trait

To implement the Add trait for a custom type, you need to define the add function. Below is an example of how to implement the Add trait for a Point struct:

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,
        }
    }
}

Explanation

  1. Importing the Add Trait: The Add trait is part of the std::ops module, which must be imported to use the add method.

  2. Defining the Struct: The Point struct is defined with two fields, x and y, both of type i32. The struct derives several traits, including Debug, Copy, Clone, and PartialEq. The PartialEq trait is particularly important as it allows for the comparison of Point instances.

  3. Implementing the Add Trait: The Add trait is implemented for the Point struct. The type Output = Self; line specifies that the result of the addition will be another Point. This is known as an associated type, which is a type that "goes together" with a trait. The add function takes two Point instances (self and other) and returns a new Point with the sum of the x and y fields.

By implementing the Add trait, you can use the + operator to add two Point instances together, resulting in a new Point with the combined coordinates. This demonstrates the power and flexibility of Rust's trait system, allowing for custom behavior with familiar operators.