【发布时间】:2015-04-11 16:34:56
【问题描述】:
我在尝试理解 Rust 生命周期在某些情况下如何工作时遇到了一些问题,如下所示。我无法让它工作,但我不知道为什么。
struct Bar {
value: &'static str,
}
struct Foo<'a, T: 'a> {
bar: &'a T,
}
fn main() {
let mut foos = Vec::new();
let y = Bar {
value: "Hello, world!",
};
let x = Foo { bar: &y };
foos.push(x);
}
error[E0597]: `y` does not live long enough
--> src/main.rs:15:25
|
15 | let x = Foo { bar: &y };
| ^ borrowed value does not live long enough
...
18 | }
| - `y` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
这是我实际尝试实现的简化示例:
fn main() {
let foos = vec![
Foo { bar: &(Bar { value: "a" }) },
Foo { bar: &(Bar { value: "b" }) },
];
}
如果有任何想法、想法或解释,我将不胜感激。
【问题讨论】: