立即丢弃向量时如何将值移出向量?

Lis*_*one 5 rust borrow-checker

我正在接收字符串矢量形式的数据,并且需要使用值的子集填充结构,如下所示

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],
    };
}
Run Code Online (Sandbox Code Playgroud)

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

常规解决方案是swap_remove,但是这是有问题的,因为不能以相反的顺序访问元素(假设结构是从上到下填充的)。

我现在通过执行a mem::replace并使用dataas来解决此问题mut,这会使本来很干净的代码变得混乱:

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())
    };
}
Run Code Online (Sandbox Code Playgroud)

此解决方案是否有替代方法,不需要我不必要地进行所有这些replace调用?datamut

Fre*_*ios 5

我一直处于这种情况,我发现的最干净的解决方案是创建一个扩展:

trait Extract: Default {
    /// Replace self with default and returns the initial value.
    fn extract(&mut self) -> Self;
}

impl<T: Default> Extract for T {
    fn extract(&mut self) -> Self {
        std::mem::replace(self, T::default())
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的解决方案中,您可以将其替换为std::mem::replace

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

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

fn main() {
    let mut data: Vec<String> = serde_json::from_str(JSON).unwrap();
    let _a = A {
        third: data[2].extract(),
        first: data[0].extract(),
        fifth: data[4].extract(),
    };
}
Run Code Online (Sandbox Code Playgroud)

这基本上是相同的代码,但它更具可读性。


如果你喜欢有趣的事情,你甚至可以写一个宏:

macro_rules! vec_destruc {
    { $v:expr => $( $n:ident : $i:expr; )+ } => {
        let ( $( $n ),+ ) = {
            let mut v = $v;
            (
                $( std::mem::replace(&mut v[$i], Default::default()) ),+
            )
        };
    }
}

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

#[derive(Debug)]
struct A {
    third: String,
    first: String,
    fifth: String,
}

fn main() {
    let data: Vec<String> = serde_json::from_str(JSON).unwrap();

    vec_destruc! { data =>
        first: 0;
        third: 2;
        fifth: 4;
    };
    let a = A { first, third, fifth };

    println!("{:?}", a);
}
Run Code Online (Sandbox Code Playgroud)


Sve*_*ach 1

另一种选择是使用 的向量Option<String>。这使我们能够将值移出,同时跟踪已移动的值,因此它们不会随向量一起删除。

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(),
};
Run Code Online (Sandbox Code Playgroud)