是否可以临时拥有struct字段?

时间:2018-11-15 03:57:08

标签: rust

我有一个不变的数据结构,还有一个更新函数,该函数获取数据结构的所有权并返回一个新的数据结构:

enum Immutable {
    Item(i32)
}

fn update(imm: Immutable) -> Immutable {
    match imm {
        Immutable::Item(x) => Immutable::Item(x + 1)
    }
}

我需要将数据结构存储在容器的可变字段中

struct State {
    item: Immutable
}

我想为State写一个命令更新函数,以调用函数更新程序:

fn update_mut(st: &mut State) -> () {
    let mut owned = Immutable::Item(42); // junk
    std::mem::swap(&mut st.item, &mut owned);
    st.item = update(owned);
}

此代码有效,但是使用mem::swap并分配垃圾对象似乎很愚蠢。我真的很想写:

fn update_mut_type_error(st: &mut State) -> () {
    let mut owned = Immutable::Item(42); // junk
    std::mem::swap(&mut st.item, &mut owned);
    st.item = update(st.item); // type error
}

有什么办法解决这个问题?或者,即使看起来有些虚假,我也必须在这里使用mem::swap

Example on Rust Playground

1 个答案:

答案 0 :(得分:-2)

相关问题