Reputation: 5877
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?
Upvotes: 1
Views: 1013
Reputation: 27546
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.
Upvotes: 6
Reputation: 3055
Well, there are 2 options:
foo
inside files main_one.rs
and main_two.rs
:// main_one.rs
mod foo {
// code
}
// main_two.rs
mod foo {
// code
}
#[path = "..."]
attribute on mod declaration. E.g. with files foo-for-one.rs
and foo-for-two.rs
:// main_one.rs
#[path = "foo-for-one.rs"]
mod foo;
// main_two.rs
#[path = "foo-for-two.rs"]
mod foo;
mod
keyword is used either to declare inner module inside of file (like in p. 1) or to add file module to crate (like mod my_mod_name;
). In second case, if you don't write this mod
declaration, it wouldn't be added to your crate. It is often used for conditional compilation:
// Enable some more features if user requested it.
#[cfg(feature = "my_extra")]
mod my_extra_features;
// Choose different code for different OSes.
#[cfg_attr(windows, path = "windows_impl.rs")]
#[cfg_attr(unix, path = "unix_impl.rs")
mod os;
Upvotes: 1