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:
rustfn 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:
vec_stringsis aVec<String>containing twoStringelements.- Using
.iter()to obtain an iterator forvec_strings, which yields references to each element in theVec<String>. - Using
.map(AsRef::as_ref)to convert each&Stringreference into a&str. - Using
.collect()to gather elements from the iterator and combine them into a newVec<&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 回复