Is mod.rs really necessary?

I was recently checking out some big Go repos, and I have to say - not having a separate file that JUST imports and exports all files in a subdirectory is nice.

I've seen far to often dry mod.rs files that look like this:

mod one;
mod two;

pub use one::*;
pub use two::*;

So I wonder - is having mod.rs really that necessary?
Can't rustc just create this module with folder name based on the fact that the *.rs files are in it and reexport everything?

I get that there is an argument of stuff that are not necessary needed to be exported like utility helpers specific to this module/folder, but this could be opt-in towards usability.

Not necessarily, because mod my_mod; is equivalent to

mod my_mod { /* contents of my_mod.rs or my_mod/mod.rs goes here */ }

so you can probably do this:

mod one {
    mod first_file_in_one;
    mod second_file_in_one;
}
pub use one::*;
1 Like

I've always liked how Rust is explicit about things. This included. In this case I like it because:

  1. Now I don't have to find some doc to understand how to opt my util helpers out of the default behaviour.
  2. Exporting everything is not common. At least in my experience, I don't think I've ever exported everything from a module. But maybe that is just because I don't use the * for re-exports. I might have done it unconsciously for some data model modules, but for logic related code I just always have a big portion of private things in modules which the public things call out to.
6 Likes

Not all .rs files are part of a crate though! Common examples are target dependent code, which is usually splitted in separate files and included only for the correct target, and main.rs/custom binaries, which are their own crates separate from the one for lib.rs

5 Likes

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.