How do you organize Rust modules?

mod.rs in directory, it's better

20%

is there more than one way? (mod.rs)

10%

my_module.rs in parent directory

10%

I like turtles

60%

10 votes ยท Closed

Rust now supports two ways to organize multi-file modules.

The traditional way, which is like Python's __init__.py:

lib.rs
my_module/
    mod.rs
    my_submodule.rs
    another_submodule.rs

One advantage is that the whole module is in one directory

The new alternative:

lib.rs
my_module.rs
my_module/
    my_submodule.rs
    another_submodule.rs

One advantage is that you don't have dozens of files with the same name (mod.rs)

Which way do you prefer?

(I'm having a hard time getting used to the new way and am thinking of reverting back, so I'm curious if I'm missing something...)

Marco Alka's photo

It's so confusing to have multiple mod.rs files open in the IDE, and I'd love to give them better names. However, it seems I somehow missed this new feature and I cannot find anything on the internet (though I also have to say that finding information on file hierarchy in Rust is a problem on its own...). Can you send me a link?

Even though I'd gladly use it, I think that the new alternative has a number of downsides:

  • When viewing the file and directory in a file explorer, they might be visually separated, which adds to confusion.
  • The module files might get mixed up with other regular files and it is difficult to tell them apart.

However, I think that a good IDE should somehow bring the files and folders back together. Maybe just display modules instead of actual files.

Mark's photo

Yeah I found it while searching searching some error messages I got while upgrading. Took a while to find back, but here it is: doc.rust-lang.org/nightly/edition-guide/rus.. (along with the other changes)

j's photo

I currently use the old structure for all my projects. personally the isolation that every module is one folder to me makes more sense. on the other hand having n mod files isn't that explicit either esp. if you have some shared logic for the specific module.

It's a tough one, I stick with the old one till I see a valid reason to switch besides eventual naming collisions. Which is weird since in other languages I always would try to avoid it ....

Not much help I guess :) Maybe I am missing something else Marco Alka what do you think?