mod.rs in Rust 2018: yes or no?
Rust 2018 changed the way modules work so that instead of having a module defined as <module>/mod.rs with other submodules in the <module>/ directory, you can now use <module.rs> outside of the directory, but keep submodules in <module>/. I've tried both ways, but I think I still prefer doing things the old way with mod.rs, since it keeps the entire module in a single, self-contained directory, which seems a bit more organized to me than putting them side-by-side. What does everyone else think?
Posted Mar 27, 2019, 2:58 PM UTC
I haven't done too much with Rust 2018 yet, but I expect I'll stick to mod.rs. I prefer containing everything in the directory.
Depends on the content of mod.rs. If it's empty or some cursory re-export statements, I'd put it in the same directory for modularity's sake. Otherwise it should warrant its own file.
Huh? It's its own file either way...
My
mod.rsfiles rarely have anything other than re-exports. (At least, that's my memory speaking. I've written a lot ofmod.rsfiles, so I wonder how many have more than just re-exports.)In any case, your advice seems orthogonal to the OP's question...
I came from Java and I still don't get why we need mod.rs can't it be just the filename and the directory structure.?
"need" is such a harsh word. Every module has some root to it, so if you want to put a module into a directory, you need some place for the root of the module to exist. In Rust 2015, that place was
mod.rsinside of the module sub-directory. I personally like that style because it serves as a nice sentinel and keeps every part of a module contained in a single sub-directory. Rust 2018 added another way to do this, where if you have a directory for a sub-modulefoo, then you can put the root of that module infoo.rsinstead, wherefooandfoo.rsare siblings in your directory hierarchy.But how come directory with .rs files isn’t implicitely a module if mod.rs is mostly just used to declare submodules?