Rust没有两个闭包,即使完全相同,也有相同的类型[重复]

cvxl0en2  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(72)

此问题在此处已有答案

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

ojsjcaue

ojsjcaue1#

你必须显式地告诉vec持有盒装trait对象:

fn main() {
    let mut vec: Vec<Box<dyn Fn()>> = Vec::new();
    vec.push(Box::new(|| println!("test")));
    vec.push(Box::new(|| println!("test2")));
    
    vec.iter().for_each(|f| (f)());
}

字符串
另一方面,你可以保持它的状态,并使用as关键字“强制转换”装箱对象:

fn main() {
    let mut vec = Vec::new();
    vec.push(Box::new(|| println!("test")) as Box<dyn Fn()>);
    vec.push(Box::new(|| println!("test2")));
    
    vec.iter().for_each(|f| (f)());
}


请注意,您只需要执行一次,因为现在rust将推断vec的类型确实是Vec<Box<dyn Fn()>>,并且进一步推送将知道自动执行此转换。

相关问题