Scope for "use"?

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"


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

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![];
        for c in dirs {
        Content { files: f, dirs: d }

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

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


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.