January 2018
Beginner to intermediate
454 pages
10h 8m
English
We can also have types in a trait that need to be specified. For instance, let's implement the Add trait from the standard library on our Point type that we declared earlier, which allows us to use the + operator on our own types:
use std::ops::Add; impl Add<Point> for Point { type Output = Point; fn add(self, point: Point) -> Self::Output { Point { x: self.x + point.x, y: self.y + point.y, } } }
The first line is to import the Add trait from the standard library so that we can implement it on our type. Here we specify that the associated Output type is Point. Associated types are most useful for return types. Here, the Output of the add() method is the associated Self::Output type.
Now, we can use the + operator on Point ...
Read now
Unlock full access