生命周期
前一章说过一件事:引用必须始终指向有效的数据。Rust 编译器要保证这条规则——它得知道"这个引用能存活多久"以及"被引用的值能存活多久",然后检查前者是否短于后者。
这个"能存活多久"就是生命周期(lifetime)。大多数时候编译器自动推断,你根本感觉不到;但遇到函数返回引用、struct 里放引用这类场景,你要显式标注。这一章讲清楚。
1. 一个不加生命周期就报错的例子
返回两个 &str 里较长的那个:
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() { x } else { y }
}
编译不过,报错:
error[E0106]: missing lifetime specifier
help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`
编译器的问题:返回的引用是借自 x 还是借自 y? 因为它决定"返回值能活多久"——如果借自 x,就要等 x 结束;如果借自 y,就要等 y 结束。编译器不知道,你要告诉它。
修复:加生命周期标注:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
含义:"x、y、返回值 共享同一个生命周期 'a——返回值的生命周期不长于 x 和 y 中较短的那个"。