2

的文档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,
        }
    }
}

为什么文档的作者在Self这里使用,而不是按名称提及Point?有技术上的区别,还是纯粹为了风格点?

4

1 回答 1

7

主要原因有两个:

  • 灵活性。如果您决定更改类型的名称,那么它就少了一个需要更新的地方。
  • 简明。SelfMyTypeor更短SomeOtherType,尤其是ThisTypeWithGenerics<'a, 'b, A, String>

是否有技术差异

是和不是,取决于你如何看待它。Self是关于泛型已“完全填充”的类型。这在以下情况下是相关的:

struct Container<T>(T);

impl<T> Container<T> {
    fn replace<U>(self, new: U) -> Self {
        Container(new)
    }
}
error[E0308]: mismatched types
 --> src/lib.rs:5:19
  |
3 | impl<T> Container<T> {
  |      - expected type parameter
4 |     fn replace<U>(self, new: U) -> Self {
  |                - found type parameter
5 |         Container(new)
  |                   ^^^ expected type parameter `T`, found type parameter `U`
  |
  = note: expected type parameter `T`
             found type parameter `U`
  = note: a type parameter was expected, but a different one was found; you might be missing a type parameter or trait bound
  = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

Self是完整类型Container<T>而不是类型构造函数Container。这可能会导致难以理解的错误

也可以看看:

于 2020-03-10T20:39:13.740 回答