How to avoid .rs file to define a module implicitly?


It seems Rust always defines a new module for each .rs files. And this makes some trouble with me because I prefer to make one source file for one entity(struct/enum or function) and organize them using directory.

If I make foo/ and put Bar2 struct in it, Rust makes two modules.

foo1::bar2::Bar2 // I `bar2` module is better to disappear.

If I follow my preferred policy (one file for one entity), I’ll get too many small unnecessary modules, and need to import them, re-expert them to container modules. And usually, names of the small modules are duplicated with the entity name regardless of suitability. I want to define modules only where necessary.

If I want to organize my entities and modules properly, I have to put too many entities into one file. This makes the file too long and harder to navigate between entities.

How can I avoid .rs files to define modules automatically? It would be better if I can make Rust to define modules only for directories. Actually I don’t know why logical module structure must be matched to physical directory/file structure, but if it has to, I think considering directories only would be far nicer…


Because it makes it a lot easier to switch between modules and files if they have the exact same structure. If you know what something is called, you know which file it’s in. This helps enormously if you need to read someone else’s code.

The best way would probably be to re-export the contents of modules.

mod bar2;
pub use self::bar2::Bar2;

If you’re feeling lazy, you can use wildcards, but I don’t recommend it since it negates the whole “if you know what something is called you know where it is” thing:

mod bar2;
pub use self::bar2::*;

What you definitely should not do is use include! to textually dump the contents of into the directory’s That’ll lead to weird source code that is likely to confuse and frustrate anyone else working on the code.


I agree that logical/physical uniformity helps navigation a lot.

But even with considering it, directories are modules, files are not modules – a directory defines a module and all symbols in files in the directory are content of the module – doesn’t hurt that module-level navigational convenience while avoiding name duplication. So I am looking for that feature, but it seems there’s no such feature.

It seems I have to start a discussion about this rather than a question.

For the textual inclusion, I agree that’s awful. I didn’t mean it. I don’t even imagine that.