gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:50:24 25 4
gpt4 key购买 nike

我正在接收字符串向量形式的数据,需要使用值的子集填充结构,例如 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,所以这应该无关紧要。

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

我现在通过执行 mem::replace 并将 data 作为 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())
};
}

是否有此解决方案的替代方案,不需要我对所有这些 replace 调用和 data 进行不必要的 mut

最佳答案

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

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())
}
}

在您的解决方案中,您可以用它替换 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(),
};
}

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


如果你喜欢搞笑,你甚至可以写一个宏:

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);
}

关于rust - 如何在立即丢弃向量时将值移出向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57685567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com