独占引用
独占引用(也称为可变引用)允许更改其所引用的值。它们的类型为 &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
andlet 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.