通过例子学习Rust

12 模块(Modules)

Rust有强大的模块系统,把代码分割为多层次的逻辑单元,并管理其可见性(公开或私有)。

模块(module)由以下条目组成:函数(fn),结构体(struct),接口(trait),实现(impl),和子模块(mod)。

fn function() { println!("called `function()`"); } // A module named `my` mod my { // A module can contain items like functions #[allow(dead_code)] fn function() { println!("called `my::function()`"); } // Modules can be nested mod nested { #[allow(dead_code)] fn function() { println!("called `my::nested::function()`"); } } } fn main() { function(); // Items inside a module can be called using their full path // The `println` function lives in the `stdio` module // The `stdio` module lives in the `io` module // And the `io` module lives in the `std` crate std::io::stdio::println("Hello World!"); // Error! `my::function` is private my::function(); // TODO ^ Comment out this line }