Return 一个引用连同 Rust 中被引用的对象

Return a reference together with the referenced object in Rust

在 Rust 中使用 Future 时,通常会在使用 lambda 实现的链式处理步骤之间传递对象的所有权(例如连接、已处理的数据等)。我理解这个概念并且已经毫无问题地做了很多。

我正在尝试做同样的事情,但这次部分结果是引用类型。我无法说服 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)
}

有问题的部分是 return 在成功分支中编辑的元组。如果我尝试 return(从而移出)范围内的拥有数据,借用检查器似乎无法理解它们之间的相关性并报告错误。

我也尝试过使用 Rc 和其他技巧,但每次都失败了。这是否可以在 Rust 中表达和修复,或者整个概念是否存在根本性缺陷并且应该以不同的方式实现,例如通过 return 将属性作为拥有的值,从而复制而不是引用?

你所拥有的本质上是一个内部引用(元组包含对其另一个元素的引用),这在 Rust 中非常棘手。借用检查器无法区分对对象本身的引用(移动并因此会使引用无效)和对象拥有的东西(例如堆上的字符串数据,这将是稳定的)。

rental crate 试图解决这个问题。您可以使用它用自定义结构替换元组,该结构能够引用它拥有的堆数据。