以下代码无法编译:
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
恰好有那个生命周期。
我想知道 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);
| ^^^^^^^^^^
这没有告诉我编译器认为装箱值的生命周期有多长。
最佳答案
I think though that the value inside of the box does live for as long as 'a since it is a member of Foo which has exactly that lifetime.
可以为 derp
成员分配一个新框,此时旧框将被删除,其中值的生命周期结束。
我认为您尝试做的事情在安全 Rust 中是不可能的:不支持结构成员之间的交叉引用。这经常作为一个问题出现,但它在该语言中不可用。
关于rust - 引用盒装值的生命周期不够长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45319021/