问题
简而言之:我正在try 实现一个struct
,其中包含对闭包的回调,该闭包以静默方式捕获状态.其 idea 是,用户提供回调(闭包),并且可以在以后发生特定事件时得到通知.
我有一个可用的概念验证版本(code sample #1).
This PoC works (code sample #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..."
This fails (code sample #2个):
与前面的 idea 相同(略有不同),但试图将闭包包含在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>`
编译器错误是非常明显的,它肯定与生命周期有关.我认为我的问题是我需要告诉编译器闭包和它的参数生命周期-但问题是,如何?
我应该如何修改code sample #2以获得像code sample #1中那样的回调注册工作?
代表: