我知道鲁斯特有一个学习曲线,但我并不希望这么快就打到它。我一直试图弄清楚这种类型不匹配已经有一段时间了,而且我没有取得任何进展。
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();
}
我的闭包上对visit_dirs
barfs的调用:
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
什么是for<'r>
的东西?为什么这种类型不匹配发生。它看起来对我好,但当然,我不知道我在寻找什么。 : - )
答案 0 :(得分:1)
与往常一样,我在将问题发布到SO后五分钟找到答案。
visit_dirs()
函数采用特征对象!因此,将&
置于闭包前面可以解决我的不匹配问题。