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!