我在读《铁 rust 书》的lifetimes chapter篇,在我的有生之年,我遇到了这个例子:
struct Foo<'a> {
x: &'a i32,
}
fn main() {
let x; // -+ x goes into scope
// |
{ // |
let y = &5; // ---+ y goes into scope
let f = Foo { x: y }; // ---+ f goes into scope
x = &f.x; // | | error here
} // ---+ f and y go out of scope
// |
println!("{}", x); // |
} // -+ x goes out of scope
我很清楚,编译器阻止的错误是分配给x
的引用的use-after-free:内部作用域完成后,f
和&f.x
变得无效,不应该分配给x
.
我的问题是,使用explicit 'a
的生存期,可以很容易地分析出这个问题,例如,通过推断对更大范围的引用的非法分配(x = &f.x;
).
在哪些情况下,在空闲(或其他类)后,需要显式生命周期来阻止使用错误?