Rust iterate over two arrays with ownership

Viewed 98

How is it possible to consume two arrays at the same time ? zip will only give references while I need the actual objects to add them in a map.

let array1 : &[String] = &["abc".to_string(),"bcd".to_string()]
let array2 : &[String] = &["bcd".to_string(),"abc".to_string()]


for a,b in array1.into_iter().zip(array2.into_iter()){
  map.insert(a,b); // Doesn't work because a and b are &String instead of String
}
1 Answers

Your variables array1 and array2 are not arrays, they are immutable references to slices, similar but not the same. You cannot take ownership of data hidden behind an immutable reference. As such, .into_iter() will yield &Strings, the fault is not due to .zip().

What you want is something like this:

let array1 = ["abc".to_string(), "bcd".to_string()];
let array2 = ["bcd".to_string(), "abc".to_string()];

for (a, b) in array1.into_iter().zip(array2.into_iter()) {
    map.insert(a, b);
}
Related