2
votes

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.

2
Can you show your match attempt? Did you remove the unwrap() call? Note that parse() returns a Result so it'd be Ok and Err rather than Some and None. - John Kugelman

2 Answers

3
votes

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
};
-3
votes

TryFrom could help you.

use std::convert::TryFrom;

fn example(v: i32) -> Option<i8> {
    i8::try_from(v).ok()
}

src: How do I convert between numeric types safely and idiomatically?