上QQ阅读APP看书,第一时间看更新
Mutable references
If we want to be able to mutable thought a reference, we need a mutable reference, since everything is immutable by default in Rust. To get a mutable reference, simply replace & with &mut. Let's write a function that will increment the x field of a Point:
fn inc_x(point: &mut Point) { point.x += 1; }
Here, we see that the Point type is now &mut, which allows us to update the point in the method. To use this method, our p1 variable needs to be mut and we also need to take a mutable reference for this variable:
let mut p1 = Point { x: 1, y: 2 }; inc_x(&mut p1);