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

Posted

技术标签:

【中文标题】如何在 Rust 中传递对可变数据的引用?【英文标题】:How do I pass a reference to mutable data in 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) 【参考方案1】:

引用也需要标记为可变:

addPoint(&mut game);

【讨论】:

以上是关于如何在 Rust 中传递对可变数据的引用?的主要内容,如果未能解决你的问题,请参考以下文章

Rust 中的可变引用传递

对于 Rust 中的多个可变引用,同步如何成为问题?

如何使 Rust 可变引用不可变?

在 Rust 的循环中更改可变引用

rust - 为什么对已删除对象的可变引用仍算作可变引用?

如何在 Rust 中修复“.. 在循环的上一次迭代中可变地借用”?