gpt4 book ai didi

rust - 是否可以从另一个成员闭包中调用一个成员闭包?

转载 作者:行者123 更新时间:2023-11-29 08:18:07 25 4
gpt4 key购买 nike

我在我的结构上使用回调,使用盒装闭包。但是,我一直无法弄清楚如何从一个闭包调用另一个闭包:

struct MyStruct {
first: Box<Fn()>,
second: Box<Fn()>,
}

impl MyStruct {
fn method(&mut self) {
self.second = Box::new(|| {
// How can I make this work?
(self.first)();
});
}
}

fn main() {
let _ = MyStruct {
first: Box::new(|| {}),
second: Box::new(|| {}),
};
}

这给出:

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:8:32
|
8 | self.second = Box::new(|| {
| ________________________________^
9 | | // How can I make this work?
10 | | (self.first)();
11 | | });
| |_________^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 7:5...
--> src/main.rs:7:5
|
7 | / fn method(&mut self) {
8 | | self.second = Box::new(|| {
9 | | // How can I make this work?
10 | | (self.first)();
11 | | });
12 | | }
| |_____^
= note: ...so that the types are compatible:
expected &&mut MyStruct
found &&mut MyStruct
= note: but, the lifetime must be valid for the static lifetime...
= note: ...so that the expression is assignable:
expected std::boxed::Box<(dyn std::ops::Fn() + 'static)>
found std::boxed::Box<dyn std::ops::Fn()>

我不太确定在这种情况下这意味着什么。

我知道借用规则是错误的原因,但是 Rust 中是否有任何合法的方法来获得与我想要的相同的效果?

我不确定我为什么要这样做是否有意义。这是一个最小的复制品。我可以提供一个更大的例子,但涉及更多。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com