我试图得到一个部分应用函数的列表,如下所示:
fn partially_applied() -> Vec<Box<dyn Fn(u32) -> u32>> {
let xs = vec![1_u32, 2, 3];
xs.into_iter().map(|x| Box::new(move |y| x + y)).collect()
}
编译器向我生成一个错误:
错误[E0277]:类型为std::vec::vec<;标准::盒装::盒装<;dyn std::ops::Fn(u32)->;u32>>;无法从类型为std::boxed::Box<;的元素上的迭代器生成;[closure@src/梅因.rs:4:41:4:57]>;
随后的try 也没有成功:
1.
fn partially_applied_with_explicit_collect_type() -> Vec<Box<dyn Fn(u32) -> u32>> {
let xs = vec![1_u32, 2, 3];
xs.into_iter().map(|x| Box::new(move |y| x + y)).collect::<Vec<Box<dyn Fn(u32) -> u32>>>()
}
fn partially_applied_with_explicit_vec_type() -> Vec<Box<dyn Fn(u32) -> u32>> {
let xs = vec![1_u32, 2, 3];
let mut res: Vec<Box<dyn Fn(u32) -> u32>> = xs.into_iter().map(|x| Box::new(move |y| x + y)).collect();
res
}
fn partially_applied_with_explicit_push() -> Vec<Box<dyn Fn(u32) -> u32>> {
let xs = vec![1_u32, 2, 3];
let mut res = vec![];
for x in xs {
res.push(Box::new(move |y| x + y));
}
res
}
只有这个try 最终成功了!
fn partially_applied_with_explicit_push_and_vec_type() -> Vec<Box<dyn Fn(u32) -> u32>> {
let xs = vec![1_u32, 2, 3];
let mut res: Vec<Box<dyn Fn(u32) -> u32>> = vec![];
for x in xs {
res.push(Box::new(move |y| x + y));
}
res
}
当涉及到动态闭包时,为什么类型推断如此糟糕?
为什么collect
在第一次try 中不起作用?
有没有更好的方法来利用类型推理来表达这样的 idea ?