如何在Rust中传递对可变数据的引用? [英] How do I pass a reference to mutable data in Rust?
本文介绍了如何在Rust中传递对可变数据的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在堆栈上创建一个可变结构,并通过辅助函数对其进行突变.
I want to create a mutable struct on the stack and mutate it from helper functions.
#[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`
我在做什么错了?
推荐答案
该引用也需要标记为可变的:
The reference needs to be marked as mutable too:
addPoint(&mut game);
这篇关于如何在Rust中传递对可变数据的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文