我在尝试理解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" }) },
];
}
我很感激任何想法、思路或解释。
foos
?例如:让 foos2: Vec<_> = foos()。我尝试了类似于 "fn foos<T>() -> Vec<Foo<T>> { }" 的东西,但它说有类型不匹配的问题。 - caio