25

I want to create a mutable struct on the stack and mutate it from helper functions.

#[derive(Debug)]
struct Game {
    score: u32,
}

fn addPoint(game: &mut Game) {
    game.score += 1;
}

fn main() {
    let mut game = Game { score: 0 };

    println!("Initial game: {:?}", game);

    // This works:
    game.score += 1;

    // This gives a compile error:
    addPoint(&game);

    println!("Final game:   {:?}", game);
}

Trying to compile this gives:

error[E0308]: mismatched types
  --> src/main.rs:19:14
   |
19 |     addPoint(&game);
   |              ^^^^^ types differ in mutability
   |
   = note: expected type `&mut Game`
              found type `&Game`

What am I doing wrong?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Wilfred Hughes
  • 29,846
  • 15
  • 139
  • 192

1 Answers1

31

The reference needs to be marked as mutable too:

addPoint(&mut game);
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Wilfred Hughes
  • 29,846
  • 15
  • 139
  • 192