【问题标题】:Is it possible to have a module which is partially accessible outside of a crate and partially only inside the crate?是否有可能有一个模块可以在板条箱外部部分访问,而部分只能在板条箱内部访问?
【发布时间】:2017-07-25 21:04:26
【问题描述】:

有没有比把所有东西都放在同一个模块中更好的方法?

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 的所有字段都必须是公开的。这两个选项都允许从我的 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( /* */ ) { /* */ };
}

然而,这似乎真的违反直觉,因为通常调用者是正在行动的东西,而函数变量是被行动的东西,这样做显然不是这种情况。所以还是想知道有没有更好的办法...

【问题讨论】:

    标签: module rust public rust-crates


    【解决方案1】:

    您可以使用新稳定的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,
    }
    

    除了crate,您还可以使用super 指定它只对父模块公开。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      • 2018-02-21
      • 2011-01-25
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多