Question about T=Self

Hello,
I am quite new to Rust. I don't understand the code below. The problem is the definition of the trait Add. I don't know the meannig of the suffix<T=Self>. I know the meaning of Self: This is the type of the current object. For example Self is Pointin fn add(&self, other:&(i32,i32))->Self in impl Add<(i32,i32)> for Point.
But I don't understand why this suffix is necessary for the compilation.

struct Point<T>{
    x:T,
    y:T
}
trait Add<T=Self>
{
    fn add(&self, other:&T)->Self;
    
}

impl Add<(i32,i32)> for Point<i32>
{
    fn add(&self, other:&(i32,i32))->Self
    {
        Point{x:self.x+other.0, y:self.y+other.1}
    }
}
 
fn main()
{

}

It's a default for the type parameter.

It means you can refer to Add without any type parameters and it will assume T is Self, or you can specify it manually like Add<u64> and then the default value is ignored.

Since a lot of arithmetic operations end up being mostly used in contexts where both operands are the same type, it can be convenient to not have to specify T.

3 Likes

For example, if you want to implement Point + Point, you can simply write

impl Add for Point { /* ... */ }

and it's equivalent to explicitly writing

impl Add<Point> for Point { /* ... */ }

or indeed

impl Add<Self> for Point { /* ... */ }

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.