我如何返回两个值,其中一个引用另一个

问题描述 投票:0回答:1

B包含对A的引用:

struct A;

struct B<'t> {
    a_ref: &'t A,
}

我的目标是编写一个简单的函数f,使以下两个等价(尽管一个可以使用堆)。

let (a, b) = f();
let a = A { };
let b = B { a_ref: &a };

我将如何写f?这是一个尝试:

fn f<'t>() -> (A, B<'t>) {
    let a = A { };
    let b = B { a_ref: &a };
    (a, b)
}

但是它无法编译出两个错误,据我所知,但不确定如何避免:

error[E0515]: cannot return value referencing local variable `a`

error[E0505]: cannot move out of `a` because it is borrowed

我看过Why can't I store a value and a reference to that value in the same struct?。上面,我写了两行代码来创建AB。我的问题不是为什么我抽象这两行的尝试失败了。我的问题是如何抽象(类似于)这两行。

rust lifetime
1个回答
0
投票

所以这里的问题是f向其调用者授予a的所有权:

  1. af内部创建。 a属于f
  2. [f返回a,将所有权转移给其调用者。
  3. [a现在已从f移动到调用者。]移动的问题在于它们有权在内存中移动变量。这将使对该变量的所有引用无效,因此,无论何时移动变量,都不允许引用。
  4. [您可以做的是让f收到对a的引用,并返回一个对B的引用的新aexample

否则,我不知道您将如何拥有这样的功能。也许唯一的方法是使用std::pin使a不可移动。但是我猜那不是您想要的。

© www.soinside.com 2019 - 2024. All rights reserved.