此问题在此处已有答案:
Expected closure, found a different closure(2个答案)
4天前关闭。
如何将两个具有相同定义的闭包放入Vec
中?
下面是一个最小可重复的示例:
fn main() {
let mut vec = Vec::new();
vec.push(Box::new(|| println!("test")));
vec.push(Box::new(|| println!("test2")));
vec.iter().for_each(|f| (f)());
}
字符串
编译失败,出现以下错误:
error[E0308]: mismatched types
--> src/main.rs:4:23
|
3 | vec.push(Box::new(|| println!("test")));
| -- the expected closure
4 | vec.push(Box::new(|| println!("test2")));
| -------- ^^^^^^^^^^^^^^^^^^^^ expected closure, found a different closure
| |
| arguments to this function are incorrect
|
= note: expected closure `[closure@src/main.rs:3:23: 3:25]`
found closure `[closure@src/main.rs:4:23: 4:25]`
= note: no two closures, even if identical, have the same type
= help: consider boxing your closure and/or using it as a trait object
型
1条答案
按热度按时间ojsjcaue1#
你必须显式地告诉
vec
持有盒装trait对象:字符串
另一方面,你可以保持它的状态,并使用
as
关键字“强制转换”装箱对象:型
请注意,您只需要执行一次,因为现在rust将推断
vec
的类型确实是Vec<Box<dyn Fn()>>
,并且进一步推送将知道自动执行此转换。