如何将 Vec<String> 转换为 &[&str]?

Eva*_*oll 3 string vector type-conversion rust

我曾经广泛使用Vec<&str>,但 Discord 上有人建议我将其更改为&[&str],但在某些情况下这会产生问题。以这段曾经有效的代码为例,

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(); 
}
Run Code Online (Sandbox Code Playgroud)

当我将第二行更改为

let pos: &[&str] = pos.iter().map(AsRef::as_ref).collect(); 
Run Code Online (Sandbox Code Playgroud)

我收到错误,

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]`
Run Code Online (Sandbox Code Playgroud)

我怎样才能将 a 转换Vec<String>&[&str]. 我从 StackOverflow 上的这个答案中得到了这个方法,我尝试移植到该方法&[&str],但没有成功。

小智 6

一个简单的方法是使用.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();
Run Code Online (Sandbox Code Playgroud)

但是,也许存在更好的解决方案