【发布时间】: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