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?
String to Vec<u8> : let my_string: String = "some string". to_owned(); let my_bytes: Vec<u8> = my_string. into_bytes();
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 use
ing 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With