以下Rust代码无法编译:
enum Foo {
Bar,
}
impl Foo {
fn f() -> Self {
Self::Bar
}
}
错误消息让我困惑:
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
。
enum Foo {
Bar,
}
impl Foo {
fn f() -> Self {
Foo::Bar
}
}
为什么不能在这种情况下使用Self
?哪里可以使用Self
*?还有什么我可以用来避免在方法体中重复类型名称吗?
*我忽略了在特征中的用法,其中Self
指的是实现特征的任何类型。
需要注意的一件重要事情是错误表示相关项目。 enum Foo { Baz }
没有相关的项目。特征可以有一个关联的项目:
trait FooBaz { type Baz }
// ^~~~~~~~ - associated item
总结一下:
为什么不能在这种情况下使用
Self
?
因为this issue。 RFC 2338有not been implemented yet。
Self
似乎是一个类型别名,虽然有一些修改。
哪里可以使用
Self
?
自我只能用于特征和impl
s。这段代码:
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
这可能是暂时的情况,将来可能会发生变化!
更确切地说,Self
应仅用作方法签名的一部分(例如fn self_in_self_out(&self) -> Self
)或访问相关类型:
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
}
}
如果枚举名称Foo
实际上很长,并且您希望避免在实现中重复它,那么您有两个选择:
use LongEnumName as Short
在模块级别。这将允许您在Short::Bar
结束时返回f
。use LongEnumName::*
在模块级别,允许更短的Bar
。如果省略pub
,则导入将是内部的,不会影响模块的公共API。
枚举构造函数!=关联项。
这是一个已知的issue,但预计不会被修复,至少在可预见的未来不会。从我收集的内容来看,让这个工作起来并不是一件容易的事。此时,更有可能改进相关文档或错误消息。
关于相关项目的主题我几乎找不到文件;然而,Rust Book有一章关于associated types。此外,在Self
有很多关于this related question的好答案。
有一个experimental feature可以让你的例子没有任何其他变化。你可以在你的主文件中添加它,在每晚的Rust版本中试一试:
#![feature(type_alias_enum_variants)]
您可以在tracking issue中跟踪功能的稳定性。