Rename `mod.rs` to `_mod.rs`

I like having the module file inside it's directory but code editors sort files alphabetically, which mixes mod.rs with other files and can't be found at a glance.

|   main.rs
+---foo
        bar.rs
        mod.rs	<-- far away from `/foo`, mixed with other files, weird
        zar.rs
|   main.rs
+---foo
        _mod.rs	<-- right below foo/, above all files, makes sense
        bar.rs
        zar.rs

I found here that using [#path="foo/_mod.rs"] was possible...

#[path="foo/_mod.rs"]
mod foo;

fn main() {
    foo::bar::my_function();
}

...but I would need to write that for every import in a file.

Is there a way to configure Cargo to recognise _mod.rs as a module instead of mod.rs?

(if this is possible for bin/, main.rs, lib.rs or other similar file/dir name, that would be cool too)

5 Likes

You can also rename foo/mod.rs to just foo.rs without having to do anything else special.

2 Likes

That's true, but It doesn't fix the problem that the module file and directory aren't next to one another.

|   foo.rs 	<-- far away from `/foo`, mixed with other files, weird
|   main.rs
+---foo
        bar.rs
        zar.rs

...unless you sort alphabetically with no separation between files and directories (in VSCode: "explorer.sortOrder": "mixed") which just looks very wrong to me.

1 Like

What an awesome insight. I spent lots of time looking for mod.rs, lib.rs and main.rs files in folders and have not realized such an easy solution could exist. The Sass compiler already allows to use underscore prefixes and just ignores them from the module name.

1 Like

This could also be handled at the IDE level. intellij-rust already sorts mod.rs first (in some windows), but not lib.rs or any others.

image

1 Like

Using _mod.rs is an interesting idea.

If ergonomics are the issue, one can define a (proc1-)macro that does the #[path = ...] for you:

_mod!(bar);

// expands to
#[path = "bar/_mod.rs"]
mod bar;

What do you think of that?


1 Curiously a non procedural macro does not work.

2 Likes

Yeah, custom sort order in the editor would be perfect. Unfortunately, VSCode doesn't support it yet.

This is sooort of off-topic, but I wonder: are you (or have you ever been grin) a Windows user?

Having gotten used to intermixed files and directories (in macOS and Linux) the Windows collation scheme looks very wrong to me! (honestly, it kind of drives me crazy.)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.