一个 Rust 模块怎么能与同一个命名空间中的常量同名?



>我在一段已发布的代码中遇到了一些代码,这些代码具有类似于以下结构的内容(编译和运行良好(:

pub mod foo {
pub const BAR: u32 = 53;
#[allow(non_snake_case)]
pub mod BAR {
pub fn eep() {
println!("This is attached to BAR");
}
}
}
fn main() {
println!("Hello, world!, {}", foo::BAR);
foo::BAR::eep();
}

这对我来说似乎很奇怪和有趣。奇怪的位BAR被定义为constmod

这是惯用的 Rust 吗?

这是怎么回事?我应该能够在文档中找到这个吗?这样的模式什么时候有效?

我可以看到这可能很有用,但是有一些真正引人注目的用例吗?

不,这不是惯用语,编译器已经告诉你这一点:

warning: module `BAR` should have a snake case name
--> src/main.rs:4:13
|
4 |     pub mod BAR {
|             ^^^ help: convert the identifier to snake case: `bar`
|
= note: #[warn(non_snake_case)] on by default

无论出于何种原因,警告已在您提供的代码中静音。

通常,在编程时,不能将相同的标签附加到同一命名空间中的多个构造

没错。模块和常量位于不同的命名空间中。有三个命名空间:

  • 类型
fn main() {
macro_rules! BAR { () => {} }
mod BAR {}
let BAR = 1;
}

模块位于类型命名空间中。

我不明白BAR是什么。它是一个模块,还是一个常量?

各有一个。

另请参阅:

  • 为什么具有子模块和名称冲突的函数的模块可以工作?

我可能会写这个:

pub mod foo {
use std::fmt;
pub const BAR: Bar = Bar(53);
pub struct Bar(u32);
impl Bar {
pub fn eep(&self) {
println!("This is attached to Bar");
}
}
impl fmt::Display for Bar {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
}
fn main() {
println!("Hello, world!, {}", foo::BAR);
foo::BAR.eep();
}

最新更新