Module 是否可能有一个模块,该模块部分可在板条箱外部访问,部分只能在板条箱内部访问?
有没有比把所有东西都放在同一个模块里更好的方法 子模块.rsModule 是否可能有一个模块,该模块部分可在板条箱外部访问,部分只能在板条箱内部访问?,module,rust,public,rust-crates,Module,Rust,Public,Rust Crates,有没有比把所有东西都放在同一个模块里更好的方法 子模块.rs pub struct GiantStruct { /* */ } impl GiantStruct { // this method needs to be called from outside of the crate. pub fn do_stuff( /* */ ) { /* */ }; } pub mod sub_module; use sub_module::GiantStruct; pub str
pub struct GiantStruct { /* */ }
impl GiantStruct {
// this method needs to be called from outside of the crate.
pub fn do_stuff( /* */ ) { /* */ };
}
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
}
}
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( /* */ ) { /* */ };
}
lib.rs
pub struct GiantStruct { /* */ }
impl GiantStruct {
// this method needs to be called from outside of the crate.
pub fn do_stuff( /* */ ) { /* */ };
}
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
}
}
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( /* */ ) { /* */ };
}
问题在于GiantStructBuilder::new_giant_struct()
;此方法应创建一个新的GiantStruct
,但要执行此操作,您需要pub fn new()。这两个选项都允许从我的板条箱外部进入
在写这个问题时,我意识到我可以这样做:
子模块.rs
pub struct GiantStruct { /* */ }
impl GiantStruct {
// this method needs to be called from outside of the crate.
pub fn do_stuff( /* */ ) { /* */ };
}
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
}
}
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 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