snippetrustMajor
Convert Vec<String> into a slice of &str in Rust?
Viewed 0 times
slicestrconvertvecruststringinto
Problem
Per Steve Klabnik's writeup in the pre-Rust 1.0 documentation on the difference between
I have a
String and &str, in Rust you should use &str unless you really need to have ownership over a String. Similarly, it's recommended to use references to slices (&[]) instead of Vecs unless you really need ownership over the Vec.I have a
Vec and I want to write a function that uses this sequence of strings and it doesn't need ownership over the Vec or String instances, should that function take &[&str]? If so, what's the best way to reference the Vec into &[&str]? Or, is this coercion overkill?Solution
You can create a function that accepts both
&[String] and &[&str] using the AsRef trait:fn test>(inp: &[T]) {
for x in inp { print!("{} ", x.as_ref()) }
println!("");
}
fn main() {
let vref = vec!["Hello", "world!"];
let vown = vec!["May the Force".to_owned(), "be with you.".to_owned()];
test(&vref);
test(&vown);
}Code Snippets
fn test<T: AsRef<str>>(inp: &[T]) {
for x in inp { print!("{} ", x.as_ref()) }
println!("");
}
fn main() {
let vref = vec!["Hello", "world!"];
let vown = vec!["May the Force".to_owned(), "be with you.".to_owned()];
test(&vref);
test(&vown);
}Context
Stack Overflow Q#41179659, score: 77
Revisions (0)
No revisions yet.