Rust生命周期

Rust生命周期

Rust中生命周期是编译器用来跟踪引用的有效范围、防止悬垂引用(被引用的内容已经释放)的核心机制

语法格式

'开头的小写字母如'a'ctx

fn longest<'a> (x: &'a str, y: &'a str) -> &'a str{
    if x.len() > y.len() { x } else { y }
}

生命周期的三大规则

  1. Rust在大多数情况下自动推断生命周期
// 编译器自动推断为:fn foo<'a, 'b>(x: &'a i32, y: &'b i32)
fn foo(x: &i32, y: &i32) -> &i32 { /* ... */ }

// 推断为:fn bar<'a>(x: &'a i32) -> &'a i32
fn bar(x: &i32) -> &i32 { x }

//在方法中,self 的生命周期自动赋予所有输出生命周期。
impl<'a> Struct<'a> {
    // 推断为:fn method(&'a self) -> &'a str
    fn method(&self) -> &str { /* ... */ }
}

生命周期在结构体中的使用

  1. 当结构体持有引用时,必须显式标注生命周期,确保结构体实例的生命周期不超过其引用的数据
struct Book<'a> {
    title: &'a str, // 引用必须比结构体实例存活更久
    author: &'a str,
}

fn main() {
    let title = String::from《Rust编程》;
    let author = String::from("张三");
    let book = Book {
        title: &title,
        author: &author,
    }; // ✅ title 和 author 的生命周期必须长于 book
}

生命周期在函数中的使用

Rust中如果函数返回引用,必须指定生命周期参数。

  1. 多个生命周期
fn compare<'a, 'b>(s1: &'a str, s2: &'b str) -> &'a str {
    // 返回值的生命周期与 s1 相同
    s1
}
  1. 生命周期参数约束, where子句约束生命周期关系
fn process<'a, 'b>(x: &'a i32, y: &'b i32) -> &'a i32
where
    'a: 'b, // 'a 必须比 'b 存活更久
{
    x
}

静态生命周期'static

'static表示引用在整个程序运行期间有效

let s: &'static str = "静态字符串";
static NUM: i32 = 42;
posted @ 2025-05-02 16:45  店里最会撒谎白玉汤  阅读(25)  评论(0)    收藏  举报