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

问题描述 投票:10回答:1

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

#[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`

我究竟做错了什么?

pointers mutable rust
1个回答
12
投票

引用也需要标记为可变:

addPoint(&mut game);
© www.soinside.com 2019 - 2024. All rights reserved.