this post was submitted on 08 Nov 2023
13 points (88.2% liked)
Rust
6041 readers
9 users here now
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Wormhole
Credits
- The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
Best to not think of files as modules. Instead a rust crate is just a tree of modules with the
src/main.rs
orsrc/lib.rs
being the main entry point.Inside these files you define the module structure you want like:
This creates two modules,
crate::foo
andcrate::foo::bar
. Now, because you don't want to have all your code in main.rs/lib.rs rust lets you move the module contents to separate files. But the location of the file needs to match its location in the module structure - from the crates root (not the file it was declared in).So when you call
mod foo;
fromsrc/main.rs
it will look forsrc/foo.rs
orsrc/foo/mod.rs
(and you can only have one of these). And thefoo::bar
- no matter if that is declared insrc/main.rs
(as above) or insidesrc/foo.rs
orsrc/foo/mod.rs
, it will always look for thebar
module contents insidesrc/foo/bar.rs
orsrc/foo/bar/mod.rs
as it is nested inside thefoo
module - not because the file is next to the current one.This means if you had this inside main.rs/lib.rs:
Then it will look for the
baz
module contents insidesrc/foo/bar/baz.rs
orsrc/foo/bar/baz/mod.rs
- even though those might be the only two files you have.