通过理解 < em > lexical 生命周期是什么,最容易理解什么是非词汇生命周期。在 Rust 的非词汇生命周期出现之前的版本中,这段代码将会失败:
fn main() {
let mut scores = vec![1, 2, 3];
let score = &scores[0];
scores.push(4);
}
Rust 编译器发现 scores被 score变量借用,因此它不允许 scores的进一步变异:
error[E0502]: cannot borrow `scores` as mutable because it is also borrowed as immutable
--> src/main.rs:4:5
|
3 | let score = &scores[0];
| ------ immutable borrow occurs here
4 | scores.push(4);
| ^^^^^^ mutable borrow occurs here
5 | }
| - immutable borrow ends here
然而,人们可以看到这个例子过于保守: score是 从没用过!问题在于,score对 scores的借入是 < em > lexical ーー这种借入一直持续到包含 scores的区块的末端:
fn main() {
let mut scores = vec![1, 2, 3]; //
let score = &scores[0]; //
scores.push(4); //
// <-- score stops borrowing here
}