4

I have a Rust module breakfast containing two sub modules egg and bacon. The breakfast module must know about egg and bacon, but the two children do not need to and therefore should not know about each other.

This is what my code looks like now. The breakfast gets made, but unfortunately egg and bacon can access each other.

mod breakfast {
    pub fn make_breakfast() -> String {
        format!("{} and {}", egg::EGG, bacon::BACON)
    }

    mod egg {
        pub const EGG: &'static str = "egg";
    }

    mod bacon {
        pub const BACON: &'static str = "bacon";

        // Oh no! The bacon knows about the egg!
        // I want this to be a compile error.
        use super::egg::EGG;
    }
}

Can I hide the siblings from each other somehow, perhaps by using visibility modifiers or by restructuring the modules? Or is the unneeded visibility something I should accept?

In reality, the modules are in separate files, but I put them in one here to make a clearer example.

4

1 回答 1

2

这是设计使然:

Rust 的名称解析在命名空间的全局层次结构上运行。层次结构中的每个级别都可以被认为是某个项目。这些物品是上述物品之一,但也包括外部板条箱。可以将声明或定义新模块视为将新树插入到定义位置的层次结构中。[...]

默认情况下,Rust 中的所有内容都是私有的,但有两个例外: pub Trait 中的关联项默认是公开的;默认情况下,pub 枚举中的枚举变体也是公共的。当一个项目被声明为 pub 时,它可以被认为是外部世界可以访问的。

由于项目是公共的或私有的,Rust 允许在两种情况下访问项目:

  • 如果一个项目是公共的,那么m如果您可以从m. 您还可以通过再导出来命名该项目。[...]
  • 如果一个项目是私有的,它可以被当前模块及其后代访问。

有关这方面的更多信息,请参阅参考资料的相关章节

于 2019-08-06T10:22:02.907 回答