Skip to content

Rust 生命周期

概述

生命周期确保引用的有效性。

🕐 生命周期语法

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

fn main() {
    let string1 = String::from("abcd");
    let string2 = "xyz";
    let result = longest(string1.as_str(), string2);
    println!("The longest string is {}", result);
}

继续学习下一章 - Rust Slice(切片)类型

本站内容仅供学习和研究使用。