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.

1
  • 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. Commented Sep 3, 2020 at 14:51

1 Answer 1

5

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
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.