Wie kann ich das mutieren einer struct s Feld von einer Methode?

Ich dies tun möchten:

struct Point {
    x: i32,
    y: i32,
}

impl Point {
    fn up(&self) {
        self.y += 1;
    }
}

fn main() {
    let p = Point { x: 0, y: 0 };
    p.up();
}

Aber dieser code löst einen compiler-Fehler:

error[E0594]: cannot assign to field `self.y` of immutable binding
 --> src/main.rs:8:9
  |
7 |     fn up(&self) {
  |           ----- use `&mut self` here to make mutable
8 |         self.y += 1;
  |         ^^^^^^^^^^^ cannot mutably borrow field of immutable binding
InformationsquelleAutor alxkolm | 2014-11-19
Schreibe einen Kommentar