如何在Rust中传递对可变数据的引用?

时间:2014-05-09 21:41:25

标签: pointers mutable rust

我想在堆栈上创建一个可变结构,并从辅助函数中改变它。

#[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);
}

尝试编译它会给出:

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

我做错了什么?

1 个答案:

答案 0 :(得分:10)

引用也需要标记为可变:

addPoint(&mut game);