乐闻世界logo
搜索文章和话题

How do I convert a Vec< String > to Vec<& str >?

1个答案

1

In Rust, Vec<String> is a vector containing multiple String instances, while Vec<&str> is a vector containing multiple string slices. To convert Vec<String> to Vec<&str>, you should create a new vector that holds references to each String in the original vector.

Here is a concrete example demonstrating this conversion process:

rust
fn main() { // Create a Vec<String> let vec_strings = vec![String::from("Hello"), String::from("world")]; // Convert Vec<String> to Vec<&str> let vec_strs: Vec<&str> = vec_strings.iter().map(AsRef::as_ref).collect(); // Output the converted result println!("{:?}", vec_strs); }

In this example:

  1. vec_strings is a Vec<String> containing two String elements.
  2. Using .iter() to obtain an iterator for vec_strings, which yields references to each element in the Vec<String>.
  3. Using .map(AsRef::as_ref) to convert each &String reference into a &str.
  4. Using .collect() to gather elements from the iterator and combine them into a new Vec<&str>.

This conversion is safe and commonly used in Rust when handling scenarios that require string slices rather than string objects.

2024年8月7日 17:24 回复

你的答案