Reputation: 8093
This is a very simple question but I can't seem to solve it. I have a string that I'd like to convert to a float. I want to catch any error in this conversion as well.
let str = "10.0"
let f: f32 = str.parse().unwrap();
How can I catch errors of the string is ""
or dog
. I was trying to use a match expression with Some and None, but I'm not sure that correct as I couldn't get it to work.
Upvotes: 2
Views: 2007
Reputation: 35560
parse
returns a Result
, not an Option
, so you should use Ok
and Err
instead of Some
and None
:
let str = "10.0";
let f: f32 = match str.parse() {
Ok(v) => v,
Err(_) => 0.0 // or whatever error handling
};
Upvotes: 5