How to collect iterator to slice of string slices to vec of string slices


#1

I’ve just started learning rust and have simple problem.

I have a simple slice of string slices like:
let a : &[&str] = &[“hello”, “world”];

I want to use iterator with it (filter it using some condition) and then collect results into Vec of string slices.

Basically help me to compile code in play rust link. I understand the error and I can fix it with longer code like creating and populating Vec by myself, but I want to understand iterators API so I hope there should be simple solution

https://play.rust-lang.org/?gist=7229026f7f71ddfb5f305fd8e7626cf9&version=stable&backtrace=0


#2

Try let v : Vec<&str> = a.into_iter().cloned().collect();. An iterator over a slice iterates over references to each of the elements, i.e. &&str, so you need to map from that to &str.

Edit: Err, actually, in this particular case, it’s probably simpler to just write a.to_vec().


#3

Thank you! It works and now I even understand why

https://play.rust-lang.org/?gist=14601ec3b598843f643588dfaffe9f0d&version=stable&backtrace=0