引用与借用

44 阅读1分钟

引用是对一个变量的“借用”,不会转移所有权。语法是:

let s1 = String::from("hello");
let len = calculate_length(&s1); // &s1 是 s1 的引用

不可变引用(&T)

fn main() {
    let s = String::from("Rust");
    print_str(&s);
    println!("s 仍然可以使用: {}", s);
}

fn print_str(s: &String) {
    println!("借用的字符串是: {}", s);
}
  • &String 是对 String不可变引用

  • 原变量 s 没有失去所有权 ✅

  • 借用期内,只能读,不能改

可变引用(&mut T)

fn main() {
    let mut s = String::from("hello");
    append_world(&mut s);
    println!("修改后的 s 是: {}", s);
}

fn append_world(s: &mut String) {
    s.push_str(", world");
}
  • 你必须将原变量定义为 mut

  • 函数参数也要是 &mut

  • 借用时使用 &mut

不能同时有可变和不可变引用

fn main() {
    let mut s = String::from("hello");

    let r1 = &s;
    let r2 = &s;
    let r3 = &mut s; // ❌ 编译错误!

    println!("{}, {}", r1, r2);
}