我想写下这个结构:
应该从A.c中借用B.c。
这是我尝试过的内容:
但它失败了。
我已经阅读了关于Rust所有权的文档,但我仍然不知道如何解决这个问题。
struct A {
b: B,
c: C,
}
struct B {
c: &C,
}
struct C;
应该从A.c中借用B.c。
A ->
b: B ->
c: &C -- borrow from --+
|
c: C <------------------+
这是我尝试过的内容:
struct 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所有权的文档,但我仍然不知道如何解决这个问题。