相关疑难解决方法(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中拥有自己的所有权?

我正在阅读有关生命周期的Rust文档.我尝试过类似的东西:

struct S {
    x: i8,
}

impl S {
    fn fun(self) {}

    fn print(&self) {
        println!("{}", self.x);
    }
}

fn main() {
    let s = S { x: 1 };
    s.fun();
    s.print();
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

error[E0382]: borrow of moved value: `s`
  --> src/main.rs:16:5
   |
15 |     s.fun();
   |     - value moved here
16 |     s.print();
   |     ^ value borrowed here after move
   |
   = note: move occurs because `s` has type `S`, which does not implement the `Copy` trait
Run Code Online (Sandbox Code Playgroud)

这是因为该 …

ownership rust

6
推荐指数
2
解决办法
666
查看次数

标签 统计

rust ×2

mutable ×1

ownership ×1

reference ×1

syntax ×1

variables ×1