以下代码无法编译:
use std::borrow::Borrow;
struct Inner<'a> {
v: Vec<&'a u8>,
}
struct Foo<'a> {
inner: Inner<'a>,
derp: Box<u8>,
}
impl<'a> Foo<'a> {
fn new() -> Foo<'a> {
let mut e = Foo {
inner: Inner { v: vec![] },
derp: Box::new(128),
};
e.inner.v.push(&*e.derp);
return e;
}
fn derp(&mut self) {
println!("{:?}", self.inner.v);
}
}
fn main() {
let mut f = Foo::new();
f.derp();
}
我收到以下错误:
error[E0597]: `*e.derp` does not live long enough
--> src/main.rs:18:25
|
18 | e.inner.v.push(&*e.derp);
| ^^^^^^^ does not live long enough
...
21 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the impl at 12:1...
--> src/main.rs:12:1
|
12 | / impl<'a> Foo<'a> {
13 | | fn new() -> Foo<'a> {
14 | | let mut e = Foo {
15 | | inner: Inner { v: vec![] },
... |
25 | | }
26 | | }
| |_^
我认为盒子里面的值确实和 'a
一样长,因为它是 Foo
的成员,它具有完全相同的生命周期 .
我想知道在新函数结束时 Foo
的移动是否令人困惑,所以如果试图在 derp
中追加 . 我得到一个不同的错误:
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
--> main.rs:20:27
|
20 | self.inner.v.push(& *self.derp);
| ^^^^^^^^^^
这并没有说明编译器认为盒装值有多长 .
1 回答
可以为
derp
成员分配一个新框,此时旧框将被删除,其中的值的生命周期结束 .我认为你想要做的事情在安全的Rust中是不可能的:不支持struct成员之间的交叉引用 . 这经常作为一个问题出现,但它只是在语言中没有 .
How to initialize struct fields which reference each other
Why can't I store a value and a reference to that value in the same struct?
您可以使用Rc解决此问题,可能与RefCell结合使用 .