首页 > 解决方案 > 是否可以将闭包分配给 impl Fn() 类型的变量?

问题描述

我能够使这段代码工作:

fn twice<T: Clone>(fst: impl Fn(T), snd: impl Fn(T)) -> impl Fn(T) {
    move |t| {
        fst(t.clone());
        snd(t)
    }
}

但是,我想要的是这个(没有拳击):

fn sub<T: Clone>(mut fst: impl Fn(T), snd: impl Fn(T)) {
    fst = move |t: T| {
        fst(t.clone());
        snd(t)
    };
}

有没有一种方法可以让第二段代码在没有装箱、使用特征、类型转换或任何其他方法的情况下工作?Rust 抱怨类型不匹配。

标签: typesrustclosures

解决方案


没有拳击就无法做到这一点。原因是fst输入中的实际类型与您稍后覆盖它的闭包类型不同。使它们具有相同类型的唯一方法是使用 trait 对象。

盒装版本可能如下所示:

use std::mem;

fn sub<'a, T: Clone + 'a>(fst: &mut Box<dyn Fn(T) + 'a>, snd: impl Fn(T) + 'a) {
    // Replace the original fst with a dummy closure while the new closure is being
    // constructed, to avoid the reference being temporarily invalid
    let fst_orig = mem::replace(fst, Box::new(|_| {}));
    *fst = Box::new(move |t: T| {
        fst_orig(t.clone());
        snd(t)
    });
}


fn main() {
    let mut f1: Box<dyn Fn(i32)> = Box::new(|x| println!("f1: {}", x));
    let f2 = |x| println!("f2: {}", x);

    sub(&mut f1, f2);

    f1(42);
}

但我真的不知道你为什么要这样做!


推荐阅读