How do you convert a Vec<String> to a &[&str] of a fixed character?

Viewed 59

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?

1 Answers

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.

Related