module - 是否有可能有一个模块,部分可以在 crate 外部访问,部分只能在 crate 内部访问?

标签 module rust public rust-crates

除了将所有内容都放在同一个模块中之外,还有什么更好的方法吗?

sub_module.rs

pub struct GiantStruct { /* */ }

impl GiantStruct {

    // this method needs to be called from outside of the crate.
    pub fn do_stuff( /* */ ) { /* */ };
}

lib.rs

pub mod sub_module;
use sub_module::GiantStruct;

pub struct GiantStructBuilder{ /* */ }

impl GiantStructBuilder{
    pub fn new_giant_struct(&mut self) -> GiantStruct {
        // Do stuff depending on the fields of the current
        // GiantStructBuilder
    }
}

问题出在 GiantStructBuilder::new_giant_struct();此方法应该创建一个新的 GiantStruct 但要执行此操作,您需要 sub_module.rs 内的 pub fn new() -> GiantStruct 或全部GiantStruct 的字段必须是公共(public)的。这两个选项都允许从我的 crate 外部进行访问。

在写这个问题时,我意识到我可以做这样的事情:

sub_module.rs

pub struct GiantStruct { /* */ }

impl GiantStruct {
    // now you can't call this method without an appropriate
    // GiantStructBuilder
    pub fn new(&mut GiantStructBuilder) -> GiantStruct { /* */ };

    pub fn do_stuff( /* */ ) { /* */ };
}
然而,这似乎确实违反直觉,因为通常调用者是正在起作用的东西,而函数变量是被作用的东西,而这样做时显然不是这种情况。所以我还是想知道有没有更好的办法...

最佳答案

您可以使用新稳定的 pub(restricted) privacy .

这将允许您仅向有限的模块树公开类型/函数,例如

pub struct GiantStruct { /* */ }

impl GiantStruct {
    // Only visible to functions in the same crate
    pub(crate) fn new() -> GiantStruct { /* */ };

    // this method needs to be called from outside of the crate.
    pub fn do_stuff( /* */ ) { /* */ };
}

或者您可以将其应用到 GiantStruct 上的字段,以允许您从 GiantStructBuilder 创建它:

pub struct GiantStruct { 
    pub(crate) my_field: u32,
}

您还可以使用 super 来指定它仅对父模块公开,而不是 crate

关于module - 是否有可能有一个模块,部分可以在 crate 外部访问,部分只能在 crate 内部访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45313433/

相关文章:

perl - 如何在与脚本相同的目录中找到 Perl 模块

memory-management - 如何在 Rust 语言中以单个字节写入/读取 8 个 true/false

java - 公共(public)字符串 - 无法解析

c++ - vector 类私有(private)/公共(public)

c - undefined symbol : PyExc_ImportError when embedding Python in C

python - 如何理解Python的模块查找

python - 如何处理分布在目录中的模块?

memory - 是否有可能在 Rust 中导致内存泄漏?

rust - 委托(delegate)数据结构的创建