这是我在Rust文档中看到的两个函数签名:
fn modify_foo(mut foo: Box<i32>) { *foo += 1; *foo }
fn modify_foo(foo: &mut i32) { *foo += 1; *foo }
Run Code Online (Sandbox Code Playgroud)
为什么不同的位置mut?
似乎第一个函数也可以声明为
fn modify_foo(foo: mut Box<i32>) { /* ... */ }
Run Code Online (Sandbox Code Playgroud) 我想在堆栈上创建一个可变结构,并从辅助函数中改变它.
#[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);
}
Run Code Online (Sandbox Code Playgroud)
试图编译这个给出:
error[E0308]: mismatched types
--> src/main.rs:19:14
|
19 | addPoint(&game);
| ^^^^^ types differ in mutability
|
= note: expected type `&mut Game`
found type `&Game`
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?