主要原因有两个:
- 灵活性。如果您决定更改类型的名称,那么它就少了一个需要更新的地方。
- 简明。
Self
比MyType
or更短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
。这可能会导致难以理解的错误。
也可以看看: