Can I Have Subfolders in a Rust "bin" project?

Hi, I have a project that is structured like this:
Screen Shot 2023-04-04 at 6.14.36 PM

Here is my code for main.rs:

mod mod1;
use crate::mod1::fn1;
mod mod2;
use crate::mod2::fn2;

fn main() {
    let sum = fn1() + fn2();

    println!("{}", sum);
}

mod1.rs

pub fn fn1() -> u8 {
    1
}

and mod2.rs

pub fn fn2() -> u8 {
    2
}

this above code works when I run it... the modules get created automatically for mod1 and mod2.

This is cool, but I am having issues when I try to make a subfolder to group related files together.

For example, if I create a folder named "nested_mod" inside of "one_plus_two" with a mod3.rs file I would expect it to create another module with the subfolder's name be able to somehow import it into main, but I don't seem to be able to do that...

Not working code:

mod mod1;
use crate::mod1::fn1;
mod mod2;
use crate::mod2::fn2;
mod nested_mod::mod3;
use crate::nested_mod::mod3::fn3;

fn main() {
    let sum = fn1() + fn2() + fn3();

    println!("{}", sum);
}

Is there some obvious proper way to do this that I'm just missing here? :thinking:

You need to create nested_mod, then pub mod mod3 within that, but you can do this inline:

mod nested_mod {
    pub(super) mod mod3; // loads nested_mod/mod3.rs
}

I showed pub(super) for just one level of exposure, but you can go further if you want.

1 Like

Huzzaaaahhhhh!!!! thank you! :+1:

Also, you can look at cargo workspaces: Cargo Workspaces - The Rust Programming Language

It will let you to have mutiple binaries and build for different platforms sharing some common code.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.