Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a vector of strings to a vector of integers in a functional way?

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>.

like image 458
Axuttaja Avatar asked Dec 04 '15 14:12

Axuttaja


1 Answers

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 collecting all of the values here, but if you only take(5) of them, you would only parse 5 of the strings.

like image 178
C. Quilley Avatar answered Sep 29 '22 19:09

C. Quilley