module - 如何在 Rust 中相互隐藏兄弟模块?

标签 module rust private class-visibility

我有一个 Rust 模块 breakfast包含两个子模块 eggbacon . breakfast模块必须知道 eggbacon , 但两个 child 不需要也不应该互相了解。

这就是我的代码现在的样子。早餐做好了,可惜eggbacon可以互相访问。

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

我能否以某种方式将 sibling 彼此隐藏起来,也许是通过使用可见性修饰符或通过重构模块?还是我应该接受不必要的可见性?

实际上,模块位于单独的文件中,但我将它们放在一个文件中以提供更清晰的示例。

最佳答案

这是设计使然:

Rust's name resolution operates on a global hierarchy of namespaces. Each level in the hierarchy can be thought of as some item. The items are one of those mentioned above, but also include external crates. Declaring or defining a new module can be thought of as inserting a new tree into the hierarchy at the location of the definition. [...]

By default, everything in Rust is private, with two exceptions: Associated items in a pub Trait are public by default; Enum variants in a pub enum are also public by default. When an item is declared as pub, it can be thought of as being accessible to the outside world.

With the notion of an item being either public or private, Rust allows item accesses in two cases:

  • If an item is public, then it can be accessed externally from some module m if you can access all the item's parent modules from m. You can also potentially be able to name the item through re-exports. [...]
  • If an item is private, it may be accessed by the current module and its descendants.

有关这方面的更多信息,请参阅The Reference的相关章节

关于module - 如何在 Rust 中相互隐藏兄弟模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57373374/

相关文章:

module - 这是在 Lua 中制作模块的正确方法吗?

magento - Mage::getStoreConfig 始终为我的自定义模块管理选项返回 null

recursion - 二叉搜索树的递归中序遍历

Scala 私有(private)应用方法?

java - Byte Buddy - 如何委托(delegate)私有(private)方法?

ruby-on-rails - 如何根据rails中的当前范围修改datagrid上的过滤器

javascript - 在类中使用 for in 循环会导致引用错误

regex - 是否有其他正则表达式语法可避免出现 “look-around, including look-ahead and look-behind, is not supported”错误?

rust - [Rust 枚举] : How to get data value from mixed type enum in rust?

c# - 私有(private)变量访问