Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading