types - 是否可以将闭包分配给 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 抱怨类型不匹配。
解决方案
没有拳击就无法做到这一点。原因是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);
}
但我真的不知道你为什么要这样做!
推荐阅读
- excel - 如何使用 Excel 的内置条件格式规则突出显示具有重复值的单元格,特别是比较 < 或 >?
- google-cloud-platform - Is there some special requirement to use Cloud Build Private Workers Pools?
- keras - Opening Phantom Zip Files with keras.utils.get_file()
- java - How to connect to Unix Domain Socket on client side service knowing only socket file descriptor
- xcode - How to use Fastlane to enable capabilities in provision profile?
- jooq - how to generate classes and properties using Entity bean class name and property names?
- typescript - 根据其他属性更改接口属性的类型
- php - custom donation amount in stripe (php)
- spring-boot - AssertionError: Status expected:<200> but was:<500> while testing getMapping with RequestParam
- flutter - TextFormField 检索焦点并在键盘关闭时重新分配初始值