相关疑难解决方法(0)

在变量名之前和":"之后放置"mut"有什么区别?

这是我在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)

variables syntax reference mutable rust

51
推荐指数
3
解决办法
5734
查看次数

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

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

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

我究竟做错了什么?

pointers mutable rust

11
推荐指数
1
解决办法
5165
查看次数

标签 统计

mutable ×2

rust ×2

pointers ×1

reference ×1

syntax ×1

variables ×1