问题
I don't understand mod or use; I suppose that mod will import files into the project and use will use them.
I have a project with this hierarchy:
.
|-- Cargo.lock
|-- Cargo.toml
|-- src
| |-- display.rs
| |-- list.rs
| |-- main.rs
| |-- parser.rs
| |-- sort.rs
Why do I need use in list.rs and not in main.rs? I use the function sorting() and print_files() in list.rs like I use the function parse() and listing() in main.rs.
main.rs
mod parser; // Ok
mod list; // Ok
mod sort; // Ok
mod display; // Ok
// use parser;// The name `parser` is defined multiple times
fn main() {
parser::parse();
list::listing();
}
list.rs
//mod sort; // file not found in module `sort`
//mod display; // file not found in module `display`
use sort; // Ok
use display; // Ok
pub fn listing() {
parcours_elements();
sort::sorting();
display::print_files();
}
fn parcours_elements() {
}
sort.rs
pub fn sorting() {
}
display.rs
pub fn print_files() {
}
回答1:
First things first, go back and re-read mod and the Filesystem. Then read it again. For whatever reason, many people have trouble with the module system. A ton of good information is contained in The Rust Programming Language.
I suppose that
modwill import files into the project andusewill use them.
mod foo "attaches" some code to the crate hierarchy, relative to the current module.
use bar avoids needing to type out the full path to something in the crate hierarchy. The path bar starts from the root of the crate.
When you have mod parser in main.rs, you are saying
go find the file parser.rs1 and put all the code in that file in the hierarchy relative to the crate root2.
When you try to then add use parser in main.rs, you are saying
go to the root of the hierarchy, find the module
parser, and make it available here (at the crate root) as the nameparser.
This already exists (because that's where the module is defined!), so you get an error.
When you have use sort is list.rs, you are saying
go to the root of the hierarchy, find the module
sort, and make it available here (inside the modulelist) as the namesort.
This works fine.
1 Or parser/mod.rs.
2 Because main.rs (or lib.rs) are the crate roots.
See also:
- Why is there a mod keyword in Rust?
- Split a module across several files
- How to include module from another file from the same project?
来源:https://stackoverflow.com/questions/52265867/why-do-i-need-use-statements-in-a-submodule-but-not-in-main-rs