How do I pass a reference to mutable data in Rust?

2019-02-16 20:03发布

问题:

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

#[deriving(Show)]
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:

rustc mutable.rs 
mutable.rs:19:18: 19:23 error: cannot borrow immutable dereference of `&`-pointer as mutable
mutable.rs:19         addPoint(&game);
                               ^~~~~
error: aborting due to previous error

What am I doing wrong?

回答1:

The borrowed pointer needs to be marked as mutable too:

addPoint(&mut game);