为什么我需要编写mod以及use何时要将模块引入范围?
mod from_other_file;
use from_other_file::sub_module;
fn main() {
sub_module::do_something();
}
Run Code Online (Sandbox Code Playgroud)
如果我这样做,则会出现错误,因为该模块未导入到当前文件中:
use from_other_file::sub_module;
fn main() {
sub_module::do_something();
}
Run Code Online (Sandbox Code Playgroud)
错误信息:
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`
Run Code Online (Sandbox Code Playgroud)
use并mod正在做两件截然不同的事情。
mod 声明一个模块。它有两种形式:
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;
Run Code Online (Sandbox Code Playgroud)
use另一方面,将项目带入当前范围。它并不参与定义哪些文件应被视为模块名称空间的一部分,而是只是将编译器已经知道的项目(例如本地声明的模块和/或文件中的外部依赖项Cargo.toml)带入范围当前文件。
| 归档时间: |
|
| 查看次数: |
2449 次 |
| 最近记录: |