I’m new to Rust and I can’t seem to figure out how to convert a Vec into an equivalent length &[&str] with a fixed character. For example, I want to convert something like ["hello", "world"] to something of the form &[&"@", &"@"].
When I try to do:
let x:Vec<String> = vec!["hello", "world"];
let mapped = x.into_iter().map(|s| "@").collect();
the compiler says:
a value of type `&[_]` cannot be built from an iterator over elements of type `&str` the trait `std::iter::FromIterator<&str>` is not implemented for `&[_]`
What is the correct way of converting a Vec<String> into a &[&str] of a singled fixed character?
>Solution :
You cannot do it since [&str] has no definite size. Try explicitly collecting into a Vec<&str> and then call as_slice on it:
let x = vec!["hello", "world"];
let mapped = x
.iter()
.map(|s| "@")
.collect::<Vec<&str>>()
.as_slice();
Also take a look at Rust’s ad-hoc conversions table as it says that as_slice() is cost-free so it should be perfectly fine to use it here I guess.