rust - 如何为结构的可变引用中的字段换入新值?

标签 rust

我有一个带有字段的结构:

struct A {
    field: SomeType,
}

给定一个 &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.
}

最终目标将等同于 get_and_set() 操作。在这种情况下,我并不担心并发性。

最佳答案

使用std::mem::swap() .

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

std::mem::replace() .

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

关于rust - 如何为结构的可变引用中的字段换入新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41370424/

相关文章:

rust - 一些关于Rust内存顺序的困惑

rust - 我怎么说一个功能仅在给定的平台上可用

rust - 如何在 Rust 中管理可选的拥有指针?

rust - 为什么在使用 Iterator::collect 时得到 "type annotations needed"?

rust - 如何将编译器标志传递给 Rust 中的子 crate ?

rust - 如何在不展开的情况下将 Option<Result<T, Error>> 转换为 Option<T>?

rust - 如何使用 Vulkano 计算着色器计算交换链图像?

Rust cargo.toml 为 C 链接器和编译器指定自定义路径

rust - rust-具有特征的泛型函数的返回类型

reference - 在引用上泛化迭代器,在值上泛化迭代器