【问题标题】:How do I pass a reference to mutable data in Rust?如何在 Rust 中传递对可变数据的引用?
【发布时间】:2014-05-09 21:41:25
【问题描述】:

我想在堆栈上创建一个可变结构并从辅助函数中对其进行变异。

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

我做错了什么?

【问题讨论】:

  • 仅供参考:约定使用fn add_point(game: &mut Game) 而不是fn addPoint (game: &mut Game)

标签: pointers mutable rust


【解决方案1】:

引用也需要标记为可变:

addPoint(&mut game);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多