迷途參照

專屬參照 (也稱做可變動參照) 允許變更自身參照的值。這類參照屬於 &mut T 型別。

fn main() {
    let mut point = (1, 2);
    let x_coord = &mut point.0;
    *x_coord = 20;
    println!("point: {point:?}");
}
This slide should take about 10 minutes.

重要須知:

  • 「專屬」表示只有這個參照可用來存取值。任何其他參照 (不論是共用或專屬參照) 都不可以同時存在,此外,在專屬參照存在的情況下,就無法存取參照的值。請嘗試在 x_coord 運作時建立 &point.0 或變更 point.0

  • Be sure to note the difference between let mut x_coord: &i32 and let x_coord: &mut i32. The first one represents a shared reference which can be bound to different values, while the second represents an exclusive reference to a mutable value.