Skip to content

Rust 引用与借用

概述

引用允许你使用值但不获取其所有权。

🔗 不可变引用

rust
fn main() {
    let s1 = String::from("hello");
    let len = calculate_length(&s1);
    println!("The length of '{}' is {}.", s1, len);
}

fn calculate_length(s: &String) -> usize {
    s.len()
}

🔗 可变引用

rust
fn main() {
    let mut s = String::from("hello");
    change(&mut s);
    println!("{}", s);
}

fn change(some_string: &mut String) {
    some_string.push_str(", world");
}

继续学习下一章 - Rust 生命周期

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