有什么方法可以装箱和移动关闭吗?

Is there any way to have boxed and by-move closures?

我需要一个按值捕获并且最多调用一次的闭包,但是我不能让函数在每个传递的闭包上都使用闭包单态化,因为闭包和函数是相互递归的,单态化阶段失败了。我试过类似的东西:

fn closure_user(closure: Box<FnOnce(usize) -> bool>) -> bool {
    closure(3)
}

fn main() {
    let big_data = vec![1, 2, 3, 4];
    closure_user(Box::new(|x| {
        let _ = big_data.into_iter();
        false
    }));
}
error[E0161]: cannot move a value of type dyn std::ops::FnOnce(usize) -> bool: the size of dyn std::ops::FnOnce(usize) -> bool cannot be statically determined
 --> src/main.rs:2:5
  |
2 |     closure(3)
  |     ^^^^^^^

开箱版本为:

fn closure_user<F>(closure: F) -> bool
where
    F: FnOnce(usize) -> bool,
{
    closure(42)
}

fn main() {
    let big_data = vec![1, 2, 3, 4];
    closure_user(|x| {
        let _ = big_data.into_iter();
        false
    });
}

似乎无法将闭包作为 FnOnce 特征对象进行装箱和拆箱。有什么方法可以装箱(无类型参数)和移动(仅调用一次)闭包吗?

这是可能的,但现在你必须通过不稳定的 std::thunk::Thunk:

use std::thunk::{Invoke, Thunk};

fn closure_user(closure: Thunk<usize, bool>) -> bool {
    closure.invoke(3)
}

fn main() {
    let big_data = vec![1, 2, 3, 4];
    closure_user(Thunk::with_arg(|x| {
        let _ = big_data.into_iter();
        false
    }));
}

这是由于当前类型系统的限制——不可能从特征对象中移出——应该尽快解决。有关详细信息,请参阅博客 post Purging Proc

从 Rust 1.35 开始,现在可以使用您的原始语法:

fn closure_user(closure: Box<dyn FnOnce(usize) -> bool>) -> bool {
    closure(3)
}

fn main() {
    let big_data = vec![1, 2, 3, 4];
    closure_user(Box::new(|x| {
        let _ = big_data.into_iter();
        false
    }));
}