为什么在具体实现中使用 Self 而不是类型名称?
Why use Self instead of the type's name in a concrete implementation?
The documentation for 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
?是技术上的差异,还是纯粹为了风格点?
主要有两个原因:
- 灵活性。如果您决定更改您的类型的名称,那么更新的地方就少了一个。
- 简洁。
Self
比 MyType
或 SomeOtherType
短,尤其是 ThisTypeWithGenerics<'a, 'b, A, String>
.
Is there a technical difference
是与否,取决于你如何看待它。 Self
是 "completely filled in" 关于泛型的类型。这在这种情况下是相关的:
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
。这会导致 hard-to-understand errors.
另请参阅:
The documentation for 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
?是技术上的差异,还是纯粹为了风格点?
主要有两个原因:
- 灵活性。如果您决定更改您的类型的名称,那么更新的地方就少了一个。
- 简洁。
Self
比MyType
或SomeOtherType
短,尤其是ThisTypeWithGenerics<'a, 'b, A, String>
.
Is there a technical difference
是与否,取决于你如何看待它。 Self
是 "completely filled in" 关于泛型的类型。这在这种情况下是相关的:
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
。这会导致 hard-to-understand errors.
另请参阅: