The best way to organize modules in a Rust project

I see some discussions about how to organize the module tree in rust, it is true that the vast majority prefer the form of organization that I have titled A in this post to make it easier to understand, however, I see many people saying that this form is old-fashioned and does not reflect the design of the current rust project, what do you prefer? The A or B format of organization? Which one really suits large projects?

A
src/
├── main.rs
├── key/
│ ├── mod.rs
│ ├── a.rs
│ └── b.rs

B
src/
├── main.rs
├── key.rs
├── key/
│ ├── a.rs
│ └── b.rs

In my experience, it doesn't matter. In my personal projects I tend to use the old module/mod.rs, but if you use module.rs in your project, I find it equally fine to navigate. Bigger projects that have many contributors, like tokio, for example, even mix both ways (not for the same module, of course, but here you have a mod.rs file for the multi_thread module, but the multi_thread::worker module places its source in worker.rs, even though it also has submodules).

2 Likes

I confess that I feel more comfortable with mod.rs, but I'm going to start using the other form so that I can analyze which one best suits my projects.

I personally prefer layout A, as it means there are fewer items in the src/ directory, and also I'm coming from Python which only supports (its version of) A.

The main disadvantage with format A is you have a bunch of files named mod.rs, and the main disadvantage with format B is the main module file feeling decoupled from the submodules in a file listing. I've tried both ways and I personally prefer format B because when I'm working on something I typically just use fuzzy searching to find the file of interest, and having 12 things named mod.rs is a bit annoying. I also just generally like how it looks more :slightly_smiling_face:

If you’re using VS Code, you can improve the editor behavior:[1]

  "workbench.editor.customLabels.patterns": {
    "**/mod.rs": "${dirname}/mod.rs"
  },

This will cause the editor tabs and file name search to always include the parent directory name. You can use it for lib.rs and main.rs too, which can be duplicated even if you avoid the mod.rs style.


  1. my previous post on this subject ↩︎

3 Likes