Trait implementation syntax

use std::ops::Add;

#[derive(Debug, PartialEq)]
struct Point<T> {
    x: T,
    y: T,
}

// Notice that the implementation uses the associated type `Output`.
impl<T: Add<Output = T>> Add for Point<T> {
    type Output = Self;

    fn add(self, other: Self) -> Self::Output {
        Self {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

I could understand this syntax impl<T: Add<Output = T>> Add for Point<T>

There's another way to write that which might be easier for you to read:

impl<T> Add for Point<T>
where
    T: Add<Output = T>
{
    // ...
}

"For a generic type T, implement Add for Point<T>, but only if T implements Add with the associated Output also being T."

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.