Rust's module system is incomprehensible

Sometimes I start to think I'm as dumb as a plank when I find myself struggling for hours, googling around, reading docs, experimenting to get what should be a very simple thing working.

Then, sometimes I find a delightful thing, others don't understand it either. In this case "others" is "cargo fmt".

The situation is that I wanted to create multiple binaries from a single crate. Something on the net told me I could do this by putting my 'main' modules in src/bin. That binaries would get automatically get built for anything in there that had a main(). Seems a bit odd but I can go with it.

The rest of my modules are in src/. Except none of them are modules to my mind. They contain no "pub mod {...}. Rather apparently they become modules by virtue of having a src/lib.rs file that declares:

pub mod itc_shell;
pub mod nats_pub;
pub mod app_error;

Again a bit odd but I can go with it.

Finally I can build my binaries. With no warnings from the compiler or suggestions from clippy. They work fine.

The only hurdle then is "cargo fmt". That it turns makes me feel not so dumb as it does not understand the module system either :slight_smile:

$ cargo fmt
Error writing files: failed to resolve mod `itc_shell`: /mnt/c/Users/zicog/projects/conq_itc_link/src does not exist
$

Which is odd as that src directory of course does exist:

$ ls -l /mnt/c/Users/michael/conveqs/conq_itc_link/src
total 8
-rwxr--r-- 1 zicog zicog  109 Aug  1 09:41 app_error.rs
drwxrwxrwx 1 zicog zicog  512 Aug  1 10:19 bin
-rwxrwxrwx 1 zicog zicog 2565 Aug  1 10:48 itc_shell.rs
drwxrwxrwx 1 zicog zicog  512 Aug  1 10:48 lib
-rw-rw-rw- 1 zicog zicog   56 Aug  1 10:48 lib.rs
-rwxrwxrwx 1 zicog zicog 3180 Aug  1 10:48 nats_pub.rs
$

Any ideas?

That sounds weird. What's in the lib folder?

Nothing in that src/lib folder. It's some junk left over from some experiment at some time.

But BINGO! Having deleted it 'cago fmt' works again! :slight_smile:

Well spotted. What is all that about?

I would probably file a bug about this to rustfmt. Here is my guess as to what happened:

  1. There's a mod statement in lib.rs and a folder of the same name.
  2. rustfmt looks inside the lib folder (which would have been correct for any other filename)
  3. rustfmt finds no itc_shell.rs file in the lib folder.
  4. When finding the path to print, it gets confused about it being called lib and prints the path containing lib.rs instead of the actual path that failed.
1 Like

OK. My second rusty things issue report today.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.