You need to use &mut self
instead of &self
and make the p
variable mutable:
struct Point {
x: i32,
y: i32,
}
impl Point {
fn up(&mut self) {
// ^^^ Here
self.y += 1;
}
}
fn main() {
let mut p = Point { x: 0, y: 0 };
// ^^^ And here
p.up();
}
In Rust, mutability is inherited: the owner of the data decides if the value is mutable or not. References, however, do not imply ownership and hence they can be immutable or mutable themselves. You should read the official book which explains all of these basic concepts.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…