ICE
ICE

Reputation: 1737

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

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`

Upvotes: 9

Views: 2795

Answers (2)

harmic
harmic

Reputation: 30597

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.

Upvotes: 8

Some Name
Some Name

Reputation: 9540

Modules in Rust should be declared explicitly with mod declaration.

Without mod from_other_file; which introduces the name from_other_file into the current scope Rust knows nothing about it. The name refers to module item.

Upvotes: 4

Related Questions