为什么不能使用`Self`来引用方法体中的枚举变体?

问题描述 投票:13回答:4

以下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指的是实现特征的任何类型。

enums rust
4个回答
6
投票

需要注意的一件重要事情是错误表示相关项目。 enum Foo { Baz }没有相关的项目。特征可以有一个关联的项目:

trait FooBaz { type Baz }
//             ^~~~~~~~ - associated item

总结一下:

为什么不能在这种情况下使用Self

因为this issueRFC 2338not been implemented yet

Self似乎是一个类型别名,虽然有一些修改。

哪里可以使用Self

自我只能用于特征和impls。这段代码:

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
    }
}

我认为user4815162342 covered the rest of the answer best


4
投票

如果枚举名称Foo实际上很长,并且您希望避免在实现中重复它,那么您有两个选择:

  • use LongEnumName as Short在模块级别。这将允许您在Short::Bar结束时返回f
  • use LongEnumName::*在模块级别,允许更短的Bar

如果省略pub,则导入将是内部的,不会影响模块的公共API。


2
投票

枚举构造函数!=关联项。

这是一个已知的issue,但预计不会被修复,至少在可预见的未来不会。从我收集的内容来看,让这个工作起来并不是一件容易的事。此时,更有可能改进相关文档或错误消息。

关于相关项目的主题我几乎找不到文件;然而,Rust Book有一章关于associated types。此外,在Self有很多关于this related question的好答案。


1
投票

有一个experimental feature可以让你的例子没有任何其他变化。你可以在你的主文件中添加它,在每晚的Rust版本中试一试:

#![feature(type_alias_enum_variants)]

您可以在tracking issue中跟踪功能的稳定性。

© www.soinside.com 2019 - 2024. All rights reserved.