Why do I need to write mod
and use
when I want to bring a module to the scope?
mod from_other_file;
use from_other_file::sub_module;
fn main() {
sub_module::do_something();
}
If I do this it gives me error because the module isn't imported inside the current file:
use from_other_file::sub_module;
fn main() {
sub_module::do_something();
}
Error Message:
error[E0432]: unresolved import `from_other_file`
--> src/main.rs:1:5
|
1 | use from_other_file::sub_module;
| ^^^^^^^^^^^^^^^ use of undeclared type or module `from_other_file`
use
and mod
are doing two very different things.
mod
declares a module. It has two forms:
mod foo {
// Everything inside here is inside the module foo
}
// Look for a file 'bar.rs' in the current directory or
// if that does not exist, a file bar/mod.rs. The module
// bar contains the items defined in that file.
mod bar;
use
, on the other hand, brings items into the current scope. It does not play a part in defining which files should be considered part of which module namespaces, rather it just brings items that the compiler already knows about (such as locally declared modules and/or external dependencies from the Cargo.toml
file) into the scope of the current file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With