3

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() {

}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Mraiih
  • 141
  • 1
  • 5
  • Please review how to create a [MCVE] and then [edit] your question to include it. Specifically, there's no mention of what `mod parser` corresponds to. Even better, don't include code that isn't relevant to reproducing the problem. You probably only need 2 (maybe 3) files to demonstrate. – Shepmaster Sep 11 '18 at 01:14

1 Answers1

4

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 mod will import files into the project and use will 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 name parser.

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 module list) as the name sort.

This works fine.

1 Or parser/mod.rs.

2 Because main.rs (or lib.rs) are the crate roots.

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366