官术网_书友最值得收藏!

  • Mastering Rust
  • Rahul Sharma Vesa Kaihlavirta
  • 432字
  • 2021-07-02 13:35:19

Nested modules

The simplest way to create a module is by using the mod {} block within an existing module. Consider the following code:

// mod_within.rs

mod food {
struct Cake;
struct Smoothie;
struct Pizza;
}

fn main() {
let eatable = Cake;
}

We created an inner module named food. To create a module within an existing one, we use the mod keyword, followed by the name of the module, food, followed by a pair of braces. Within braces, we can declare any kind of item or even a nested module. Within our food module, we declared three structs: Cake, Smoothie, and Pizza. In main, we then create a Cake instance from the food module using the path syntax food::Cake. Let's compile this program:

Strange! The compiler does not see any Cake type being defined. Let's do what the compiler says and add use food::Cake:

// mod_within.rs

mod food {
struct Cake;
struct Smoothie;
struct Pizza;
}

use food::Cake;

fn main() {
let eatable = Cake;
}

We added use food::Cake;. To use any item from a module, we have to add a use declaration. Let's try again:

We get another error saying that Cake is private. This brings us to an important aspect about modules, providing privacy. Items within a module are private by default. To use any item from a module, we need to bring the item into scope. This is a two-step process. First, we need to make the item itself public by prefixing our item declaration with the pub keyword. Second, to use the item, we need to add a use statement, as we did previously with use food::Cake.

What comes after the use keyword is the item path in the module. The path to any item within a module is specified using the path syntax, which uses two double colons (::) between item names. The path syntax usually starts with the module name for importing items, though it is also used for importing individual fields of some types, such as enums.

Let's make our Cake public:

// mod_within.rs

mod food {
pub struct Cake;
struct Smoothie;
struct Pizza;
}

use food::Cake;

fn main() {
let eatable = Cake;
}

We added pub before our Cake struct and used it in the root module via use food::Cake. With those changes, our code compiles. It's not apparently clear now as to why one would need to create nested modules like so, but we'll get to see how they are used when we write tests in Chapter 3, Tests, Documentation, and Benchmarks.

主站蜘蛛池模板: 双城市| 阿拉善盟| 旌德县| 延安市| 宜丰县| 攀枝花市| 繁峙县| 双峰县| 大连市| 岳西县| 乐山市| 林甸县| 桃源县| 招远市| 巧家县| 肃宁县| 梅河口市| 怀安县| 哈巴河县| 万载县| 额尔古纳市| 江津市| 丰都县| 灌南县| 定边县| 独山县| 栖霞市| 精河县| 德格县| 瑞昌市| 清水河县| 浦东新区| 隆林| 南充市| 陆良县| 陵水| 鸡东县| 惠东县| 林芝县| 鄂托克旗| 信阳市|