立即丢弃向量时如何将值移出向量? [英] How to move values out of a vector when the vector is immediately discarded?

查看:71
本文介绍了立即丢弃向量时如何将值移出向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以字符串向量的形式接收数据,需要使用值的子集填充结构,例如 这个:

I am receiving data in the form of a string vector, and need to populate a struct using a subset of the values, like this:

const json: &str = r#"["a", "b", "c", "d", "e", "f", "g"]"#;

struct A {
    third: String,
    first: String,
    fifth: String,
}

fn main() {
    let data: Vec<String> = serde_json::from_str(json).unwrap();
    let a = A {
        third: data[2],
        first: data[0],
        fifth: data[4],
    };
}

这不起作用,因为我正在将值移出向量.编译器认为这会使 data 处于未初始化状态,这可能会导致问题,但是因为我再也不会使用 data,所以这无关紧要.

This doesn't work because I'm moving values out of the vector. The compiler believes that this leaves data in an uninitialized state that can cause problems, but because I never use data again, it shouldn't matter.

传统的解决方案是swap_remove,但它是有问题的,因为元素不是以相反的顺序访问的(假设结构从上到下填充).

The conventional solution is swap_remove, but it is problematic because the elements are not accessed in reverse order (assuming the structure is populated top to bottom).

我现在通过执行 mem::replace 并将 data 作为 mut 来解决这个问题,这会使原本干净的代码变得混乱:

I solve this now by doing a mem::replace and having data as mut, which clutters this otherwise clean code:

fn main() {
    let mut data: Vec<String> = serde_json::from_str(json).unwrap();
    let a = A {
        third: std::mem::replace(&mut data[2], "".to_string()),
        first: std::mem::replace(&mut data[0], "".to_string()),
        fifth: std::mem::replace(&mut data[4], "".to_string())
    };
}

是否有替代此解决方案的方法,它不需要我让所有这些 replace 调用和 data 不必要地 mut?>

Is there an alternative to this solution that doesn't require me to have all these replace calls and data unnecessarily mut?

推荐答案

另一种选择是使用 Option 的向量.这允许我们将值移出,同时跟踪哪些值已被移动,因此它们不会随向量一起被删除.

Another option is to use a vector of Option<String>. This allows us to move the values out, while keeping track of what values have been moved, so they are not dropped with the vector.

let mut data: Vec<Option<String>> = serde_json::from_str(json).unwrap();
let a = A {
    third: data[2].take().unwrap(),
    first: data[0].take().unwrap(),
    fifth: data[4].take().unwrap(),
};

这篇关于立即丢弃向量时如何将值移出向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆