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

I can convert Vec<String> to Vec<&str> this way:

let mut items = Vec::<&str>::new();
for item in &another_items {
    items.push(item);
}

Are there better alternatives?


There are quite a few ways to do it, some have disadvantages, others simply are more readable to some people.

This dereferences s (which is of type &String) to a String "right hand side reference", which is then dereferenced through the Deref trait to a str "right hand side reference" and then turned back into a &str. This is something that is very commonly seen in the compiler, and I therefor consider it idiomatic.

let v2: Vec<&str> = v.iter().map(|s| &**s).collect();

Here the deref function of the Deref trait is passed to the map function. It's pretty neat but requires useing the trait or giving the full path.

let v3: Vec<&str> = v.iter().map(std::ops::Deref::deref).collect();

This uses coercion syntax.

let v4: Vec<&str> = v.iter().map(|s| s as &str).collect();

This takes a RangeFull slice of the String (just a slice into the entire String) and takes a reference to it. It's ugly in my opinion.

let v5: Vec<&str> = v.iter().map(|s| &s[..]).collect();

This is uses coercions to convert a &String into a &str. Can also be replaced by a s: &str expression in the future.

let v6: Vec<&str> = v.iter().map(|s| { let s: &str = s; s }).collect();

The following (thanks @huon-dbaupp) uses the AsRef trait, which solely exists to map from owned types to their respective borrowed type. There's two ways to use it, and again, prettiness of either version is entirely subjective.

let v7: Vec<&str> = v.iter().map(|s| s.as_ref()).collect();

and

let v8: Vec<&str> = v.iter().map(AsRef::as_ref).collect();

My bottom line is use the v8 solution since it most explicitly expresses what you want.


The other answers simply work. I just want to point out that if you are trying to convert the Vec<String> into a Vec<&str> only to pass it to a function taking Vec<&str> as argument, consider revising the function signature as:

fn my_func<T: AsRef<str>>(list: &[T]) { ... }

instead of:

fn my_func(list: &Vec<&str>) { ... }

As pointed out by this question: Function taking both owned and non-owned string collections. In this way both vectors simply work without the need of conversions.