namespaces - 为什么我不能在 Trait impl block 的 match Arms 中使用 Self?

标签 namespaces rust

我可以写这个没问题:

mod sufficiently_long_namespace {
    pub enum Foo {
        Bar,
        Buzz,
        Quux,
    }
}

use std::fmt::{Display, Error, Formatter};

impl Display for sufficiently_long_namespace::Foo {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        match self {
            //-- NOTE: this works
            sufficiently_long_namespace::Foo::Bar  => write!(f, "it's Foo stuff"),
            sufficiently_long_namespace::Foo::Buzz => write!(f, "it's Buzz stuff"),
            sufficiently_long_namespace::Foo::Quux => write!(f, "it's Quux stuff"),
            //-- but this doesn't:
            // Self::Bar  => write!(f, "it's Foo stuff"),
            // Self::Buzz => write!(f, "it's Buzz stuff"),
            // Self::Quux => write!(f, "it's Quux stuff"),
        }
    }
}

fn main() {
    let test1 = sufficiently_long_namespace::Foo::Bar;
    println!("{}", test1);
}

它编译得很好。使用 Self 注释掉的版本令人惊讶的是,事实并非如此:

error[E0599]: no variant named Bar found for type sufficiently_long_namespace::Foo in the current scope

这是rustc 1.30.0-nightly (73c78734b 2018-08-05) .

我的命名空间是否搞砸了,或者这确实是一个错误?

最后,我确实想要明确的名称 impl Display for sufficiently_long_namespace::Foo ,但必须在 match 中重复此操作 ARM 看起来很笨重。

最佳答案

来自 IRC:

(01:16PM) SpaceManiac: it's more of a missing feature than a bug
(01:17PM) SpaceManiac: consider use long_ns::Foo; at the top of fmt() then Foo::Bar in the match

Rust 的用途permits renaming ,所以我可以这样做:

    use sufficiently_long_namespace::Foo as _Self;
    match self {
        _Self::Bar  => write!(f, "it's Foo stuff"),
        _Self::Buzz => write!(f, "it's Buzz stuff"),
        _Self::Quux => write!(f, "it's Quux stuff"),
    }

虽然这仍然更好:

    use sufficiently_long_namespace::Foo;
    match self {
        Bar  => write!(f, "it's Foo stuff"),
        Buzz => write!(f, "it's Buzz stuff"),
        Quux => write!(f, "it's Quux stuff"),
    }

关于namespaces - 为什么我不能在 Trait impl block 的 match Arms 中使用 Self?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51798609/

相关文章:

rust - 可以关闭的重新导出可选 cargo 功能

testing - 如何在 Rust 的实现中测试方法

Rust 告诉 '' 值移到这里,在循环的前一次迭代中”

c# - 不合格的类名与系统命名空间中的新 .NET 类发生冲突

javascript - 命名空间内的构造函数

namespaces - IPython Notebook 没有显示完整的命名空间

rust - 分割字符串并返回Vec <String>

php - 当您在具有命名空间的类的文件名中添加 .class.php 时会出现问题吗?

使用命名空间的 PHP 类会导致我的不使用命名空间的代码出现问题。为什么?

std - 使用哪个 std::sync::atomic::Ordering ?