我可以这样写:
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
的注释掉的版本没有:
错误[E0599]:在当前范围内找不到类型为
Bar
的名为sufficiently_long_namespace::Foo
的变体
这是在rustc 1.30.0-nightly (73c78734b 2018-08-05)
上。
我是否破坏了我的命名空间,或者确实是一个错误?
最后,我确实希望在中使用显式名称
impl Display for sufficiently_long_namespace::Foo
,但不得不在match
的手臂中重复这一操作似乎很麻烦。
答案 0 :(得分:2)
来自IRC:
(01:16 PM)SpaceManiac:它比错误更像是缺少的功能
(01:17 PM)SpaceManiac:考虑将use long_ns::Foo;
放在fmt()
的顶部,然后将Foo::Bar
放在比赛中
Rust的use
也是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"),
}