相关疑难解决方法(0)

如何在结构的可变引用中为字段交换新值?

我有一个带字段的结构:

struct A {
    field: SomeType,
}
Run Code Online (Sandbox Code Playgroud)

给定a &mut A,如何移动值field并交换新值?

fn foo(a: &mut A) {
    let mut my_local_var = a.field;
    a.field = SomeType::new();

    // ...
    // do things with my_local_var
    // some operations may modify the NEW field's value as well.
}
Run Code Online (Sandbox Code Playgroud)

最终目标相当于一项get_and_set()行动.在这种情况下,我并不担心并发性.

rust

16
推荐指数
2
解决办法
2788
查看次数

如何移出作为选项的struct字段?

我想收集结构的更改并立即应用它们.基本大纲如下所示:

enum SomeEnum {
    Foo,
    Bar,
}

struct SomeStruct {
    attrib: SomeEnum,
    next_attrib: Option<SomeEnum>,
}

impl SomeStruct {
    pub fn apply_changes(&mut self) {
        if let Some(se) = self.next_attrib {
            self.attrib = se;
        }
        self.next_attrib = None;
    }
}
Run Code Online (Sandbox Code Playgroud)

这会产生以下编译器错误:

error[E0507]: cannot move out of borrowed content
  --> src/lib.rs:13:27
   |
13 |         if let Some(se) = self.next_attrib {
   |                     --    ^^^^ cannot move out of borrowed content
   |                     |
   |                     hint: to prevent move, use `ref se` or `ref mut se` …
Run Code Online (Sandbox Code Playgroud)

copy rust borrow-checker

6
推荐指数
1
解决办法
723
查看次数

标签 统计

rust ×2

borrow-checker ×1

copy ×1