Home > Net >  How can I convert Vec<String> to &[&str]?
How can I convert Vec<String> to &[&str]?

Time:10-12

I use to have extensive use of Vec<&str>, but someone on Discord talked me into changing that to &[&str], however in some cases this has produced problems. Take for example this code which used to work,

fn main() { 
  let pos: Vec<String> = vec!["foo".to_owned(), "bar".to_owned(), "baz".to_owned()];
  let pos: Vec<&str> = pos.iter().map(AsRef::as_ref).collect(); 
}

When I change that second line to

let pos: &[&str] = pos.iter().map(AsRef::as_ref).collect(); 

I get the error,

error[E0277]: a value of type `&[&str]` cannot be built from an iterator over elements of type `&_`
 --> bin/seq.rs:3:51
  |
3 |     let pos: &[&str] = pos.iter().map(AsRef::as_ref).collect();    
  |                                                      ^^^^^^^ value of type `&[&str]` cannot be built from `std::iter::Iterator<Item=&_>`
  |
  = help: the trait `FromIterator<&_>` is not implemented for `&[&str]`

How can I convert a Vec<String> into a &[&str]. I got this method from this answer on StackOverflow, which I tried to port to &[&str] with no luck.

CodePudding user response:

A simple way is to use .as_slice()

let pos: Vec<String> = vec!["foo".to_owned(), "bar".to_owned(), "baz".to_owned()];
let pos: Vec<&str> = pos.iter().map(AsRef::as_ref).collect();

let pos: &[&str] = pos.as_slice();

But, perhaps a better solution exist


  • Related