问题描述
我很难解决参考和借用问题。
我的最终目标是用户可以创建机器人的实例,向其添加回调(成对的(String
,闭包)),然后调用 listen
。当机器人收到一条消息时,它会将消息的文本与闭包哈希图中的键进行比较。如果其中之一匹配,则调用相应的回调闭包。
我需要在传递给 String
的方法 b
的闭包中的 async move
块中的结构实例 b
上使用 add_closure
字段和这就是问题所在。
我尝试过的:不同的智能指针,但没有帮助。
use futures::Future;
use std::pin::Pin;
struct B {
val: String,closures: Vec<Box<dyn FnMut() -> Pin<Box<dyn Future<Output = ()>>>>>,}
impl B {
fn add_closure(&mut self,closure: Box<dyn FnMut() -> Pin<Box<dyn Future<Output = ()>>>>) {
self.closures.push(closure);
}
}
fn main() {
let mut b = B {
val: "test".to_string(),closures: vec![],};
b.add_closure(Box::new(|| {
Box::pin(async {
println!("{}",b.val);
})
}));
}
编译器的错误信息很大:
error[E0502]: cannot borrow `b` as mutable because it is also borrowed as immutable
--> src/main.rs:21:5
|
21 | b.add_closure(Box::new(|| {
| ^ - -- immutable borrow occurs here
| ______|_____________|
| | _____|
| ||
22 | || Box::pin(async {
23 | || println!("{}",b.val);
| || - first borrow occurs due to use of `b` in closure
24 | || })
25 | || }));
| ||______-^ mutable borrow occurs here
| |_______|
| cast requires that `b` is borrowed for `'static`
error[E0597]: `b` does not live long enough
--> src/main.rs:23:28
|
21 | b.add_closure(Box::new(|| {
| - -- value captured here
| ___________________|
| |
22 | | Box::pin(async {
23 | | println!("{}",b.val);
| | ^ borrowed value does not live long enough
24 | | })
25 | | }));
| |______- cast requires that `b` is borrowed for `'static`
26 | }
| - `b` dropped here while still borrowed
error: aborting due to 2 prevIoUs errors
如何使用
我需要做什么才能得到我想要的工作?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)