I am trying to parse a string in a list of floating point values in Rust. I would suggest that there is a smart way to do this with iterators and Option s; however, I cannot make it ignore Err values that are the result of failed parse () calls. The Rust tutorial does not seem to cover any examples like this, and the documentation is confusing at best.
How can I implement this using vector / list operations of a functional style? Pointers to the best rust style for my iterative implementation will also be appreciated!
"Functional" style
Panic when he meets Err
input.split(" ").map(|s| s.parse::<f32>().unwrap()).collect::<Vec<_>>()
iterative style
Ignores non-floating values as implied
fn parse_string(input: &str) -> Vec<f32> { let mut vals = Vec::new(); for val in input.split_whitespace() { match val.parse() { Ok(v) => vals.push(v), Err(_) => (), } } vals } fn main() { let params = parse_string("1 -5.2 3.8 abc"); for ¶m in params.iter() { println!("{:.2}", param); } }
functional-programming rust
Jeff
source share