Modules named mod.rs

Can someone tell me the rationale behind having to name files mod.rs rather than their actual name. I seem to be ending up with several files called mod.rs albeit in different directories which is confusing in the editor. Apart from putting everything in the crate root I can't seem to avoid having a mod.rs in say a /protocol directory and have it just have mod statements to include the modules by name that I actually want in that directory or if I move two modules encoder.rs and decoder.rs from /protocol into their own directories I again have to call them mod.rs. Am I missing something here?

Can you provide the output of find src so we know what your source tree layout looks like ?

You do not strictly have to name any file mod.rs; for any module file there are 3 alternatives:

  1. directory_of_the_parent_module/protocol/mod.rs
  2. directory_of_the_parent_module/protocol.rs
  3. Any path you like using the #[path] attribute (don't do this unless you have a serious reason, because it's confusing)

(Here directory_of_the_parent_module is src/ if the module is a child of the root.)

It is true, however, that there is no standard location for a module that is both inside "its own directory" and not named mod.rs. I recommend getting used to option 2. It has the advantage that creating child modules does not demand relocating the module's own source.

3 Likes

That was a change in the 2018 edition:
https://doc.rust-lang.org/edition-guide/rust-2018/path-changes.html#no-more-modrs

1 Like

With the 2018 edition and later, you can freely rename your protocol/mod.rs file into protocol.rs without additional work.

2 Likes

Applying the Edition 2018 approach to this situation, you'd have something like this:

main.rs:

pub mod protocol;

protocol.rs:

pub mod encoder;
pub mod decoded;

protocol/encoder.rs:

pub mod enc1;

protocol/encoder/enc1.rs:

// Rust code...

protocol/decoder.rs:

pub mod dec1;

protocol/decoder/dec1.rs:

// Rust code...
1 Like

Thanks for 2018 tip. That seems to work with having a level of indirection in the root so now I will change everything and get rid of all the mod.rs files.