为什么在具体实现中使用 Self 而不是类型的名称?

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名字?是否存在技术差异,还是纯粹为了风格点?

She*_*ter 7

有两个主要原因:

  • 灵活性。如果您决定更改类型的名称,那么更新的地方就少了一个。
  • 简明。SelfMyType或更短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。这可能会导致难以理解的错误

也可以看看:

  • 我想添加第三个原因:人类模式匹配。我的大脑似乎能够识别“self”和“Self”并对它们进行特殊处理,因此对我来说,这比解析“Point”并思考“哦,是的,当前类型”更省力。 (2认同)