这个问题在这里已有答案:
在Rust中使用 Future
时,通常会在使用lambdas实现的链接处理步骤之间传递对象的所有权(例如,连接,已处理的数据等) . 我理解这个概念并且在没有问题的情况下做了很多 .
我正在尝试做同样的事情,但这次部分结果是参考类型 . 我无法说服Rust借用检查器接受以下(过度简化)代码:
extern crate futures;
use futures::prelude::*;
// Parsed data with attribute values that might be not owned, only referenced
trait Data<'a> {
fn attribute<'s, 'n>(&'s self, name: &'n str) -> &'a str;
}
fn async_load_blob() -> Box<Future<Item = Vec<u8>, Error = ()>> {
Box::new(futures::future::err(())) // Dummy impl to compile
}
fn parse<'a>(_blob: &'a [u8]) -> Result<Box<Data<'a> + 'a>, ()> {
Err(()) // Dummy impl just to compile fine
}
fn resolve_attribute<'a, 'n>(
name: &'n str,
) -> Box<Future<Item = (Vec<u8>, &'a str), Error = ()> + 'a> {
let owned_name = name.to_owned(); // move attribute name into lambda
let fut = async_load_blob().and_then(move |blob| {
// COMPILE ERROR: how to convince borrow checker that the
// owned data is properly moved out together with the reference?
let data_res = parse(blob.as_slice());
match data_res {
Ok(data) => {
let attr = data.attribute(owned_name.as_str());
futures::future::ok((blob, attr))
}
Err(e) => futures::future::err(e),
}
});
Box::new(fut)
}
有问题的部分是在成功分支中返回的元组 . 如果我尝试从范围返回(从而移出)拥有的数据,借用检查器似乎无法理解它们之间的相关性并报告错误 .
我也尝试过使用 Rc
和其他技巧,每次都失败了 . 这是否可以在Rust中表达和修复,或者整个概念是否存在根本缺陷,应该以不同的方式实现,例如:通过将属性作为拥有值返回,从而复制而不是引用?
1 回答
你有什么基本上是一个内部引用(元组包含对其他元素的引用),这在Rust中非常棘手 . 借用检查器无法区分对象本身的引用(它移动并因此使引用无效)和对象拥有的东西(例如堆上的字符串数据,这将是稳定的) .
rental箱试图解决这个问题 . 您可以使用它来替换元组,该自定义结构能够引用它拥有的堆数据 .