说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?。上面,我写了两行代码来创建A
和B
。我的问题不是为什么我抽象这两行的尝试失败了。我的问题是如何抽象(类似于)这两行。