this post was submitted on 08 Nov 2023
12 points (87.5% liked)
Rust
7623 readers
180 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 2 years 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.rsorsrc/lib.rsbeing the main entry point.Inside these files you define the module structure you want like:
This creates two modules,
crate::fooandcrate::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.rsit will look forsrc/foo.rsorsrc/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.rsorsrc/foo/mod.rs, it will always look for thebarmodule contents insidesrc/foo/bar.rsorsrc/foo/bar/mod.rsas it is nested inside thefoomodule - 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
bazmodule contents insidesrc/foo/bar/baz.rsorsrc/foo/bar/baz/mod.rs- even though those might be the only two files you have.