相关疑难解决方法(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
查看次数

标签 统计

rust ×1