Search code examples
rust

How do I use this directory traversal code from Rust examples?


I am trying to learn Rust, and as usual, I look at code examples in the documentation and go from there. Never failed me so far. I came across this function, but don't know how to pass the second argument called "cb" which I assume means callback.

use std::io;
use std::fs::{self, DirEntry};
use std::path::Path;

// one possible implementation of walking a directory only visiting files
fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
    if dir.is_dir() {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                visit_dirs(&path, cb)?;
            } else {
                cb(&entry);
            }
        }
    }
    Ok(())
}

fn main() {
    let path = Path::new("/Users/aaron/Downloads");

    visit_dirs(path, cb);
}

Solution

  • you can use a closure (as said in the comments):

    use std::io;
    use std::fs::{self, DirEntry};
    use std::path::Path;
    
    fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
        if dir.is_dir() {
            for entry in fs::read_dir(dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.is_dir() {
                    visit_dirs(&path, cb)?;
                } else {
                    cb(&entry);
                }
            }
        }
        Ok(())
    }
    
    fn main() {
        let path = Path::new("/Users/aaron/Downloads");
    
        let cb = |entry| {
            println!("{:?}", entry);
        };
    
        visit_dirs(path, &cb);
    }