2

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.

turtle
  • 7,533
  • 18
  • 68
  • 97
  • 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 Sep 03 '20 at 14:51

1 Answers1

4

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
};
Stargateur
  • 24,473
  • 8
  • 65
  • 91
Aplet123
  • 33,825
  • 1
  • 29
  • 55