Sebastian Dine
Sebastian Dine

Reputation: 1009

Rust Vector Mapping with Strings

I have to structs with fields of type String that I want to map to each other.

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<_>>();

When I execute this, I get the following error because of missing Copy traits for the field of type String.

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

My current workaround to this issue is that in the mapping, I temporarily convert the field of type String into &str and then back again to String, which appears kind of hacky to me:

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

I wonder if there is a more elegant solution to this?

Upvotes: 1

Views: 1358

Answers (1)

cafce25
cafce25

Reputation: 27594

Depending on wether you still need a_list after the conversion you could either:

// 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();

Upvotes: 1

Related Questions