Splitting up files

It's often useful to split your code into several parts to give a logical structure to the program. In Rust, this is done with the mod keyword. With mod, we can declare that a certain module exists, and this can be done right in the middle of a program.

fn main() {
    a::x();
    b::y();
}

mod a {
    pub fn x() {}
}

mod b {
    pub fn y() {}
}

Note that I had to make x and y public. Visibility (like public and private) works on a module level in Rust.

Modules are also the way to link different files together. Let's say I have a file structure like this:

Cargo.toml
src/
    main.rs
    a.rs
    b.rs

Then I can link these files together using mod statements:

mod a;
mod b;

fn main() {
    a::x(); // assuming a has a public x function 
    b::y(); // assuming b has a public y function 
}

It is also possible to use directories to represent modules. One file in that directory then has to be called mod.rs to represent the root of that module. The file structure might look like this:

Cargo.toml
src/
    c/
        a.rs
        b.rs
        mod.rs
    main.rs

a.rs and b.rs would contain public functions, mod.rs would look like this:

#![allow(unused)]
fn main() {
pub mod a;
pub mod b;
}

to declare that there are two modules in the c/ directory. Because we want to import a and b, through c from main.rs I have to say that a and b are public. main.rs now looks like this:

mod c;

fn main() {
    c::a::x();
    c::b::y();
}

Linking between files

As you can see, the paths to refer to items in modules can become pretty long. c::a::x() may become cumbersome. To reduce the effort, there is also the use statement. mod and use together form what other languages might call import. mod makes modules available, and use can bring them into scope. For example, main.rs in the previous example could have looked like this:

mod c;

use c::a::x;
use c::b::y;

fn main() {
    x();
    y();
}

Alternatively, if we had put this in mod.rs:

#![allow(unused)]
fn main() {
pub mod a;
pub mod b;

pub use a::x;
pub use b::y;
}

Then our main.rs code would be as short as

mod c;
// because we used 'pub use` these are now directly
// available from c.
use c::{a, b};

fn main() {
    x();
    y();
}

You can play with this, making modules private but publically useing items from them to make specific parts of your program available.