The documentation for Add gives the following example:
use std::ops::Add;
#[derive(Debug, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl Add for Point {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
Why did the author of the docs use Self here, instead of mentioning Point by name? Is there a technical difference, or is it purely for style points?
There are two main reasons:
Selfis shorter thanMyTypeorSomeOtherTypeand especiallyThisTypeWithGenerics<'a, 'b, A, String>.Yes and no, depending on how you look at it.
Selfis the type that has been "completely filled in" with regards to generics. This is relevant in cases like this:Selfis the complete typeContainer<T>, not the type constructorContainer. This can cause hard-to-understand errors.See also: