简体   繁体   中英

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

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.

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


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM