为什么要这么做:
extern crate crossbeam;
fn main(){
let v: Vec<i32> = vec![1, 2, 3];
crossbeam::scope(|s|{
s.spawn(|_|{
for e in v{
println!("{}", e);
}
});
}).unwrap();
}
如果不这样做:
extern crate crossbeam;
fn main(){
let v: Vec<i32> = vec![1, 2, 3];
let closure = |_|{
for e in v{
println!("{}", e);
}
};
crossbeam::scope(|s|{
s.spawn(closure);
}).unwrap();
}
编译器给我错误:
error[E0308]: mismatched types
--> src/main.rs:11:11
|
11 | s.spawn(closure);
| ^^^^^ one type is more general than the other
|
= note: expected type `std::ops::FnOnce<(&crossbeam::thread::Scope<'_>,)>`
found type `std::ops::FnOnce<(&crossbeam::thread::Scope<'_>,)>`
是因为更高的特质界限吗?
如果是的话,如何在保持闭包定义在范围之外的同时进行修复?
我是rust的新手,我发现该错误令人困惑,因为据我所知,它找到的类型是预期的类型。
答案 0 :(得分:1)
问题在于rust无法正确地推断出封闭的类型(不做详细介绍,假设编译器在封闭之间的类型推断不太好)。
例如,您只需要在所有闭包参数上添加类型注释
extern crate crossbeam;
fn main(){
let v: Vec<i32> = vec![1, 2, 3];
let closure = |sr:& crossbeam::thread::Scope<'_> /* anotate the closure arguments types */|{
for e in v{
println!("{}", e);
}
};
crossbeam::scope(|s|{
s.spawn(closure);
}).unwrap();
}
类似