Ben*_*son 2 traits self-type rust
的文档Add给出了以下示例:
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,
}
}
}
Run Code Online (Sandbox Code Playgroud)
为什么文档的作者在Self这里使用,而不是提到Point名字?是否存在技术差异,还是纯粹为了风格点?
有两个主要原因:
Self比MyType或更短SomeOtherType,尤其是ThisTypeWithGenerics<'a, 'b, A, String>。有技术差异吗
是和否,取决于你如何看待它。Self是关于泛型已经“完全填充”的类型。这在这样的情况下是相关的:
struct Container<T>(T);
impl<T> Container<T> {
fn replace<U>(self, new: U) -> Self {
Container(new)
}
}
Run Code Online (Sandbox Code Playgroud)
struct Container<T>(T);
impl<T> Container<T> {
fn replace<U>(self, new: U) -> Self {
Container(new)
}
}
Run Code Online (Sandbox Code Playgroud)
Self是完整的类型Container<T>,而不是类型构造函数Container。这可能会导致难以理解的错误。
也可以看看: