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

Rust's modules

Before going any further, we need to talk about how file hierarchy works in Rust through its modules.

The first thing to know is that files and folders are handled as modules in Rust. Consider the following:

|- src/
    |
    |- main.rs
    |- another_file.rs

If you want to declare that a module is in the another_file.rs file, you'll need to add to your main.rs file:

    mod another_file;

You will now have access to everything contained in another_file.rs (as long as it's public).

Another thing to know: you can only declare modules whose files are on the same level as your current module/file. Here's a short example to sum this up:

|- src/
    |
    |- main.rs
    |- subfolder/
        |- another_file.rs

If you try to declare a module referring to another_file.rs directly into main.rs, as shown preceding, it'll fail because there are no another_file.rs in src/. In this case, you'll need to do three things:

  1. Add a mod.rs file into the subfolder folder.
  2. Declare another_file into mod.rs.
  3. Declare subfolder into main.rs.

You certainly wonder, why mod.rs? It's the norm in Rust—when you import a module, which is a folder, the compiler will look for a file named mod.rs into it. The mod.rs files are mainly used for re-exporting modules' content outside.

Let's now write down the code to do this:

Inside mod.rs:

    pub mod another_file;

Inside main.rs:

    mod subfolder;

Now, you can use everything that is in another_file (as long as it's public!). Consider the following example:

    use subfolder::another_file::some_function;

You will certainly have noticed that we declared another_file publicly in mod.rs. It's simply because main.rs won't be able to access its content otherwise, as it's not at the same module level. However, a child module can access a parent's private items.

To conclude this small part, let's talk about the third type of modules: the module blocks (yes, as simple as that).

Just like you import a file or a folder, you can create a module block by using the same keyword:

    mod a_module {
      pub struct Foo;
   }

And you now created a new module named a_module containing a public structure. The rules described previously are applied the same way to this last kind of module.

You now know how to use modules to import files and folders. Let's start writing down our game!

主站蜘蛛池模板: 大港区| 宁南县| 尚义县| 九龙县| 宜兰市| 东宁县| 栖霞市| 嘉荫县| 杂多县| 招远市| 白沙| 稻城县| 临江市| 香港 | 绥芬河市| 宁津县| 饶阳县| 买车| 纳雍县| 凌源市| 祥云县| 陵川县| 郑州市| 道孚县| 兰州市| 台山市| 库伦旗| 阳春市| 方正县| 民勤县| 文安县| 营口市| 连州市| 定陶县| 上犹县| 长沙县| 丘北县| 永靖县| 探索| 新和县| 陇南市|