I'm trying to convert Vec<&str>
to Vec<u16>
but I can't figure out a functional way to do it.
let foo: &str = "1,2,3"; // Parsing a string here
let bar: Vec<&str> = foo.split(",").collect(); // Bar is a nice vector of &str's
I need to get bar
into a Vec<u16>
.
There's an iterator adapter map
! You'd use it like this:
let bar: Vec<u16> = foo.split(",").map(|x| x.parse::<u16>().unwrap()).collect();
parse
is a library function that relies on the trait FromStr
, and it can return an error, so we need to unwrap()
the error type. (This is a good idea for a short example, but in real code, you will want to handle the error properly - if you have a value that's not a u16
there, your program will just crash).
map
takes a closure that takes it's parameter by value and then returns the iterator obtained by lazily applying that function. You're collect
ing all of the values here, but if you only take(5)
of them, you would only parse 5 of the strings.
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