Scope for "use"?

Hi,
I'm a bit puzzled by "scope" of "use". The following program doesn't compile, the line
use rayon::iter::ParallelIterator; must be placed before usage of par_iter() and in the top section.
The only dependency is
rayon = "1.2.1"

Code:

use rayon::iter::IntoParallelRefIterator;
use std::fs;
use std::fs::DirEntry;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

#[derive(Debug)]
struct Content {
    files: Vec<PathBuf>,
    dirs: Vec<PathBuf>,
}

impl Content {
    fn build(files: Vec<PathBuf>, dirs: Vec<Content>) -> Content {
        let mut f = vec![];
        let mut d = vec![];
        f.extend_from_slice(&files);
        for c in dirs {
            f.extend_from_slice(&c.files);
            d.extend_from_slice(&c.dirs);
        }
        Content { files: f, dirs: d }
    }
}

fn main() {
    let content = get_file_list(PathBuf::from("."));
    println!(
        "dirs: {}, files: {}",
        content.dirs.len(),
        content.files.len()
    );
}

fn get_file_list(path: PathBuf) -> Content {
    let files = fs::read_dir(&path)
        .map_err(|e| format!("Unable to read dir: {}", e))
        .unwrap();
    let list: Vec<DirEntry> = files
        .into_iter()
        .map(|r| r.expect(format!("Unable to read dir").as_str()))
        .collect();
    //use rayon::iter::ParallelIterator; // Uncomment this line to build successfully
    let files: Vec<PathBuf> = list
        .par_iter()
        .filter(|e| e.file_type().expect("cant get type").is_file())
        .map(|file| file.path())
        .collect();
    let dirs: Vec<Content> = list
        .par_iter()
        .filter(|e| e.file_type().expect("cant get type").is_dir())
        .map(|dir| {
            let mut c = get_file_list(dir.path());
            c.dirs.push(dir.path());
            c
        })
        .collect();
    Content::build(files, dirs)
}

To put it simply, the scope of use is the enclosing curly brackets. In technical terms, it's either a module or a block.

So in your case, use rayon::iter::ParallelIterator is effective only inside the get_file_list function, but for its whole body.

Reference.

Thanks,
So two follow-up questions:

  1. Why doesn't the same rule apply to other 'use' ?
  2. Why do I need 'use rayon...' in both places: top of the file and method?

Thank you.

The two uses are different.

use rayon::iter::IntoParallelRefIterator;
use rayon::iter::ParallelIterator;

Your code compiles find if the second one is up at the top with the first.

Sorry, that was really silly of me. Thanks a lot.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.