Day 4:可變引用(&mut)

學習目標

  • 學會可變引用 &mut
  • 理解可變引用的嚴格規則
  • 能避開常見的可變/不可變衝突錯誤

今日重點

可變引用

fn change(s: &mut String) {
    s.push_str(", world");   // 借來還可修改內容
}

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

規則:同一時間只能有一個可變引用

let mut s = String::from("hello");
let r1 = &mut s;
let r2 = &mut s;   // 錯誤!同時兩個可變引用

規則:可變引用不能與不可變引用混用

let mut s = String::from("hello");
let r1 = &s;        // 不可變引用
let r2 = &s;        // 不可變引用(OK)
let r3 = &mut s;    // 錯誤!已有不可變引用在用
println!("{} {}", r1, r2);

正確做法:使用範圍分開

let mut s = String::from("hello");
{
    let r1 = &s;
    let r2 = &s;
    println!("{} and {}", r1, r2);  // 最後一次使用,結束
}
let r3 = &mut s;    // 已經沒有其他引用,OK
println!("{}", r3);

練習

  1. 故意寫「兩個可變引用」的程式,讀懂編譯器錯誤。
  2. {} 範圍讓可變引用合法。
  3. 思考:為什麼 Rust 要限制「一可變或多多不可變」?(答案:避免資料競爭)

自我檢查

  • 會宣告可變引用 &mut
  • 知道同時只能一個可變引用
  • 能用範圍(block)讓引用合理共存
  • 能解釋這是為了避免資料競爭

深入連結

  • The Book 第 4 章「Mutable References」