Rust Vector映射与字符串



我必须将字段类型为String的结构体相互映射。

struct A {
name: String,
}
struct B {
id: String
}

let a_list = vec![A {name: "a1".to_string()}, A {name: "a2".to_string()}];

let b_list = a_list.iter().map(|a| B {id: a.name}).collect::<Vec<_>>();

当我执行此操作时,我得到以下错误,因为String类型的字段缺少Copy特征。

14 |     let b_list = a_list.iter().map(|a| B {id: a.name}).collect::<Vec<_>>();
|                                               ^^^^^^ move occurs because `a.name` has type `String`, which does not implement the `Copy` trait

我目前对这个问题的解决方案是,在映射中,我暂时将类型String的字段转换为&str,然后再返回到String,这对我来说似乎有点黑客:

let b_list = a_list.iter().map(|a| B {id: a.name.as_str().to_string()}).collect::<Vec<_>>();

我想知道是否有更优雅的解决方案?

根据转换后您是否仍然需要a_list,您可以:

// if you still need a_list
let b_list: Vec<B> = a_list.iter().map(|a| B{id: a.name.clone()}).collect();
// if you don't need a_list anymore
let b_list: Vec<B> = a_list.into_iter().map(|a| B{id: a.name}).collect();

最新更新