George Madrid
George Madrid

Reputation: 703

Type mismatch with closure

I know that Rust has a learning curve, but I didn't expect to hit it so hard so soon. I have been trying to figure out this type mismatch for quite a while now, and I'm not making any progress.

struct FileInfo<'a> {
    path: &'a Path
}

fn process_file(entry: &DirEntry, map: &HashMap<&str, &FileInfo>) {
    let pathbuf = entry.path();
    let mut f = fs::File::open(pathbuf.as_path()).unwrap();
    let info = FileInfo { path: pathbuf.as_path() };
}

fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry) -> ()) -> io::Result<()> {
    // Taken from Rust read_dir docs
    // ...
}

fn main() {
    let path = Path::new("/Users/gmadrid/Media/");
    let map : HashMap<&str, &FileInfo> = HashMap::new();

    visit_dirs(path, |e: &DirEntry| process_file(e, &map)).unwrap();
}

The call to visit_dirs barfs on my closure with:

src/main.rs:51:19: 51:55 error: mismatched types [E0308]
src/main.rs:51  visit_dirs(path, |e: &DirEntry| process_file(e, &map)).unwrap();
                             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/main.rs:51:19: 51:55 help: run `rustc --explain E0308` to see a detailed explanation
src/main.rs:51:19: 51:55 note: expected type `&for<'r> std::ops::Fn(&'r std::fs::DirEntry)`
src/main.rs:51:19: 51:55 note:    found type `[closure@src/main.rs:51:19: 51:55 map:_]`
error: aborting due to previous error

What is the for<'r> stuff? and why is this type mismatch happening. It looks okay to me, but of course, I have no idea what I'm looking for. :-)

Upvotes: 2

Views: 474

Answers (1)

George Madrid
George Madrid

Reputation: 703

As always, I find the answer five minutes after posting the question to SO.

The visit_dirs() function takes a trait object! So, putting the & in front of the closure fixes my mismatch.

Upvotes: 1

Related Questions