Search code examples
rustrust-crates

Can two crates in the same project have a module with same name?


I was trying to create two modules with the same name for different crates, and was surprised that when declaring the second module, it was pointing to the code of the first. Does this mean that module definitions are coupled to the file hierarchy in addition to their place of declaration inside crates?

/src/bin/main_one.rs // contains declaration `mod foo;`
/src/bin/main_two.rs // contains declaration `mod foo;`

/src/bin/foo.rs // Thre can only ever be one foo.rs here

Would the only solution here be to have differently named modules?

src/bin/foo-for-one.rs // module used by one.rs
src/bin/foo-for-two.rs // module used by two.rs

If the same code is reached via its location in the filesystem, what's the point of the mod keyword? Is it for module privacy only?


Solution

  • I'd just use the recommended layout for binaries with multiple files:

    src/
    └── bin/
        ├── main-one/
        │   ├── main.rs
        │   └── foo.rs
        └── main-two/
            ├── main.rs
            └── foo.rs
    

    where main-one/main.rs has the contents of the previous main-one.rs and analog for main-two.
    With foo.rs directly in src/bin you'd have to stop that from being detected as binary anyways, and this way the name conflict goes away automatically.