我正在使用tokio-rs构建一个Rust服务,并且到目前为止,我对这个技术栈感到满意。现在,我正在尝试链接包含写操作的异步操作,并且在借用检查器方面遇到了困难。
我的简化的最小代码示例如下:
extern crate futures; // 0.1.21
use futures::Future;
use std::{cell::RefCell, rc::Rc};
trait RequestProcessor {
fn prepare(&self) -> Box<Future<Item = (), Error = ()>>;
fn process(&mut self, request: String) -> Box<Future<Item = (), Error = ()>>;
}
struct Service {
processor: Rc<RefCell<RequestProcessor>>,
}
impl Service {
fn serve(&mut self, request: String) -> Box<Future<Item = (), Error = ()>> {
let processor_clone = self.processor.clone();
let result_fut = self
.processor
.borrow()
.prepare()
.and_then(move |_| processor_clone.borrow_mut().process(request));
Box::new(result_fut)
}
}
fn main() {}
作为简短的总结,在异步准备步骤之后,我正在尝试运行另一个异步操作,该操作写入self的一个字段。如果没有可变性,使用普通的Rc成员可以轻松实现,但是可变性会导致出现以下错误:
error[E0597]: `processor_clone` does not live long enough
--> src/main.rs:22:32
|
22 | .and_then(move |_| processor_clone.borrow_mut().process(request));
| ^^^^^^^^^^^^^^^ - `processor_clone` dropped here while still borrowed
| |
| borrowed value does not live long enough
|
= note: values in a scope are dropped in the opposite order they are created
我觉得这应该能够正常工作,我没有看到可变引用仍然被借用的地方。 我认为
process()
应该在返回future后释放处理器的&mut self
,因此不应发生编译错误。您能否解释一下其中的原因? 如何更改此示例才能被编译器接受?