Appearance
Day 06 - 生命周期
什么是生命周期?
生命周期是Rust确保引用有效性的机制。
rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}'a 表示生命周期参数,返回值的生命周期与输入参数中最短的一致。
使用场景
rust
struct ImportantExcerpt<'a> {
part: &'a str,
}
fn main() {
let novel = String::from("Call me Ishmael...");
let first = novel.split(' ').next().unwrap();
let excerpt = ImportantExcerpt { part: first };
}📅 学习进度
| Day | 主题 | 状态 |
|---|---|---|
| 01-05 | 基础 | ✅ |
| 06 | 生命周期 | ✅ |
| 07 | 结构体 | ⬜ |
