为什么不能在方法体中使用“ Self”来引用枚举的变量? [英] Why can't `Self` be used to refer to an enum's variant in a method body?
问题描述
该问题现在已过时,因为已实现了此功能。 相关答案。
This question is now obsolete because this feature has been implemented. Related answer.
以下Rust代码无法编译:
The following Rust code fails to compile:
enum Foo {
Bar,
}
impl Foo {
fn f() -> Self {
Self::Bar
}
}
错误消息使我感到困惑:
The error message confuses me:
error[E0599]: no associated item named `Bar` found for type `Foo` in the current scope
--> src/main.rs:7:9
|
7 | Self::Bar
| ^^^^^^^^^
可以使用 Foo
而不是 Self
,但这使我感到奇怪,因为 Self
应该是指正在执行的类型(忽略特征),在这种情况下为 Foo
。
The problem can be fixed by using Foo
instead of Self
, but this strikes me as strange since Self
is supposed to refer to the type that is being implemented (ignoring traits), which in this case is Foo
.
enum Foo {
Bar,
}
impl Foo {
fn f() -> Self {
Foo::Bar
}
}
为什么 Self
在这种情况下不能使用? Self
到底可以在哪里使用 * ?还有什么我可以用来避免在方法主体中重复类型名称的东西?
Why can't Self
be used in this situation? Where exactly can Self
be used*? Is there anything else I can use to avoid repeating the type name in the method body?
* 特质,其中 Self
指实现特质的任何类型。
* I'm ignoring usage in traits, where Self
refers to whatever type implements the trait.
推荐答案
要注意的重要一点是错误表示关联的项目。 enum Foo {Baz}
没有关联的项目。一个特征可以具有一个关联的项目:
An important thing to note is that the error said associated item. enum Foo { Baz }
doesn't have associated items. A trait can have an associated item:
trait FooBaz { type Baz }
// ^~~~~~~~ - associated item
总结一下:
在这种情况下为什么不能使用 Self
?
Why can't
Self
be used in this situation?
Self
似乎充当类型别名,尽管进行了一些修改。
Self
seems to act as a type alias, albeit with some modifications.
自我
到底在哪里使用?
自我只能用于特征和 impl
中。这段代码:
Self can only be used in traits and impl
s. This code:
struct X {
f: i32,
x: &Self,
}
输出以下内容:
error[E0411]: cannot find type `Self` in this scope
--> src/main.rs:3:9
|
3 | x: &Self,
| ^^^^ `Self` is only available in traits and impls
这可能是暂时情况,将来可能会改变!
This is possibly a temporary situation and might change in the future!
更准确地说, Self
应该仅用作方法签名的一部分(例如 fn self_in_self_out(& self)-> Self
)或访问关联的类型:
More precisely, Self
should be used only as part of method signature (e.g. fn self_in_self_out(&self) -> Self
) or to access an associated type:
enum Foo {
Baz,
}
trait FooBaz {
type Baz;
fn b(&self) -> Self::Baz; // Valid use of `Self` as method argument and method output
}
impl FooBaz for Foo {
type Baz = Foo;
fn b(&self) -> Self::Baz {
let x = Foo::Baz as Self::Baz; // You can use associated type, but it's just a type
x
}
}
这篇关于为什么不能在方法体中使用“ Self”来引用枚举的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!