Why I must write `type` aliases in the operator overloading?


#1

the example on TRPL operators-and-overload

when I delete the type alias line:

impl Add for Point {    
    fn add(self, other: Point) -> Point {
        Point { x: self.x + other.x, y: self.y + other.y }
    }
}

get error:

error: not all trait items implemented, missing: `Output` [E0046]

#2

Have you read about associated types? They are a special kind of generics and the book explains them quite well.


#3

The thing here is that these are not type aliases, but rather associated types. This particular one is required in order to show rustc what the result of adding will be for your type.

In general, associated types specify some type associated and required by a trait. Kind of like type parameters (think Foo<T>), but named.

Edit: ninja, probably should just read ocean’s post.


#4

Well you are repeating yourself, the Output type is already the method’s return type. But not all traits have this repetition and it’s how you define the trait’s associated types. It’s a very handy feature.