【发布时间】:2015-02-19 17:56:23
【问题描述】:
我想写这个结构:
struct A {
b: B,
c: C,
}
struct B {
c: &C,
}
struct C;
B.c应该是从A.c借来的。
A ->
b: B ->
c: &C -- borrow from --+
|
c: C <------------------+
这是我尝试过的: 结构 C;
struct B<'b> {
c: &'b C,
}
struct A<'a> {
b: B<'a>,
c: C,
}
impl<'a> A<'a> {
fn new<'b>() -> A<'b> {
let c = C;
A {
c: c,
b: B { c: &c },
}
}
}
fn main() {}
但它失败了:
error[E0597]: `c` does not live long enough
--> src/main.rs:17:24
|
17 | b: B { c: &c },
| ^ borrowed value does not live long enough
18 | }
19 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'b as defined on the method body at 13:5...
--> src/main.rs:13:5
|
13 | fn new<'b>() -> A<'b> {
| ^^^^^^^^^^^^^^^^^^^^^
error[E0382]: use of moved value: `c`
--> src/main.rs:17:24
|
16 | c: c,
| - value moved here
17 | b: B { c: &c },
| ^ value used here after move
|
= note: move occurs because `c` has type `C`, which does not implement the `Copy` trait
我已阅读有关所有权的 Rust 文档,但我仍然不知道如何修复它。
【问题讨论】:
-
兄弟引用(即,引用同一结构的一部分)在 Rust 中是不可能的。