Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need both mod and use to bring a module to the scope?

Tags:

rust

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`
like image 203
ICE Avatar asked Jul 31 '20 23:07

ICE


Video Answer


1 Answers

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.

like image 70
harmic Avatar answered Sep 24 '22 23:09

harmic