Question about structuring a project into multiple dirs/modules

I'm new to Rust and have written a few command line utilities so far. I'm starting to write things that require more code and I'm trying to figure out how to split up my code. So far, what I've done is something like this:

src/
  main.rs
  mod1.rs
  mod2.rs

This works fine as all I have to do in main.rs is include mod mod1 and I have access to the public structs/functions. However, my modules files (mod1.rs and mod2.rs in this fictional example) are getting large enough that I'd like to break them up into separate files but include them in their own directories like this:

src/
  main.rs
  mod1/
    mod1_structs.rs
    mod1_functions.rs
  mod2/
    mod2_structs.rs
    mod2_functions.rs

In this case, including mod mod1; won't work in main.rs. How is this normally handled in Rust?

Thanks so much in advance!

First, you'll need to name your files without duplicating the module names:

src/
  main.rs
  mod1/
    structs.rs
    functions.rs
  mod2/
    structs.rs
    functions.rs

Then, in main.rs, you can write:

mod mod1 {
    mod structs;
    mod functions;
}

mod mod2 {
    mod structs;
    mod functions;
}

Now items in the sub-submodules will be accessible at paths like mod1::functions::do_stuff. If you prefer to have them accessible directly within the outer module (like mod1::do_stuff), you can re-export some or all of the submodule contents like this:

mod mod1 {
    mod structs;
    mod functions;
    pub use self::{structs::*, functions::*};
}

You can also move the code inside of the braces to a file named src/mod1.rs or src/mod1/mod.rs, and then main.rs can once again just say:

mod mod1;
2 Likes