问题
简而言之:我正在尝试实现一个struct
包含闭包回调的回调,它可变地捕获状态。想法是用户提供回调(关闭),并且可以在特定事件发生时得到通知。
我有一个有效的概念验证版本(代码示例#1)。
此 PoC 有效(代码示例 #1):
fn fun<F>(f: F) -> F
where
F: FnMut() -> (),
{
f
}
fn main() {
let mut abc = "abc".to_string();
let mut f = fun(|| {
abc.push_str(".");
println!("closure: {:?}", abc);
});
f();
f();
f();
println!("end: {:?}", abc);
}
输出:
closure: "abc."
closure: "abc.."
closure: "abc..."
end: "abc..."
这失败了(代码示例#2):
与之前的想法相同(略有不同),但试图将闭包包含在Foo
.
struct Foo<'a, T> {
pub cb: Box<dyn FnMut(&T) + 'a>,
}
impl<'a, T> Foo<'a, T> {
fn new(f: impl FnMut(&T) + 'a) -> Self {
Self { cb: Box::new(f) }
}
fn on_change(&mut self, f: impl FnMut(&T) + 'a)
{
self.cb = Box::new(f);
}
}
impl<'a, T> Default for Foo<'a, T>
{
fn default() -> Self {
Self::new(|_| {})
}
}
fn main() {
let mut abc = "abc".to_string();
let mut f = Foo::default();
f.on_change(|a| {
abc.push_str("."); // PROBLEM HERE; uncomment and it works!
println!("- param: {:?}", a);
});
let param = "a".to_string();
(f.cb)(¶m);
(f.cb)(¶m);
(f.cb)(¶m);
println!("end: {:?}", abc);
}
预期输出:
- param: "a"
- param: "a"
- param: "a"
end: "abc..."
实际输出(编译器错误):
error[E0502]: cannot borrow `abc` as immutable because it is also borrowed as mutable
--> src/main.rs:33:27
|
25 | f.on_change(|a| {
| --- mutable borrow occurs here
26 | abc.push_str("."); // PROBLEM HERE; uncomment and it works!
| --- first borrow occurs due to use of `abc` in closure
...
33 | println!("end: {:?}", abc);
| ^^^ immutable borrow occurs here
34 | }
| - mutable borrow might be used here, when `f` is dropped and runs the destructor for type `Foo<'_, String>`
编译器错误非常清楚,它肯定与生命周期有关。我认为我的问题是我需要告诉编译器有关闭包及其参数生命周期的信息 - 但问题是,如何?
我应该如何修改代码示例 #2以获得像代码示例 #1中那样的回调注册工作?
回复: