一个模块如何具有多个文件?
我不明白为什么每个模块只有一个文件.
I don't understand why we have only one file per module.
// main.rs
mod dog; // Find dog in dog.rs or dog/mod.rs
fn main() {
dog::sonic_bark();
}
当dog
变大并具有很多功能时,将所有功能都放在一个文件中是不好的.
When dog
grows larger and has lots of functions, it's not good to have all of them in one file.
我如何不使用它们就将它们分开
How I can separate them without using
dog::leg::walk();
dog::head::nose::smell();
dog::tail::iron_tail();
dog::mouth::sonic_bark();
我只想使用dog::sonic_bark();
您不能.
您可以拥有比文件更多的 模块(典型示例是mod tests
嵌套在文件中),但不能相反.
You can have more modules than files (the typical examples being mod tests
nested in the file), but not the reverse.
但是,这并不重要,因为您可以使用封装+重新导出.
However, this does not matter because you can use encapsulation + re-export.
使用mod xxx;
声明子模块时的默认值是xxx
是 private :当前模块的任何用户都不会知道它依赖于xxx
.
The default when declaring a submodule with mod xxx;
is that xxx
is private: no user of the current module will know that it depends on xxx
.
通过选择重新导出符号将其合并:
Combine this with selecting re-exporting symbols:
pub use self::leg::walk;
pub use self::head::nose::smell;
pub use self::tail::iron_tail;
pub use self::mouth::sonic_bark;
您可以直接调用它们:dog::walk()
,dog::smell()
,...
And you can call those directly: dog::walk()
, dog::smell()
, ...
因此,私人进口和公共再出口可帮助您隐藏内部层次结构,同时公开一个统一的公共界面.
Therefore, private imports and public re-exports help you have a hidden internal hierarchy while exposing a flat public interface.
完整示例:
mod dog {
pub use self::head::nose::smell;
pub use self::leg::walk;
pub use self::mouth::sonic_bark;
pub use self::tail::iron_tail;
mod leg {
pub fn walk() {}
}
mod head {
pub mod nose {
pub fn smell() {}
}
}
mod tail {
pub fn iron_tail() {}
}
mod mouth {
pub fn sonic_bark() {}
}
}
fn main() {
dog::sonic_bark();
}