How to cast a char into an interger and match arms in Rust?

Viewed 698

I'm learning Rust.

I'm using .to_digit() to cast a char to an integer, but I cannot match the casted value afterwards. Any help is appreciated!

let c: char = '2';
let to_num = c.to_digit(10);

match to_num {
    Some(2) => {println!("matched")},
    None => {},
}

Error: patterns Some(0u32..=1u32) and Some(3u32..=std::u32::MAX) not covered

1 Answers

char::to_digit returns Option<u32>, representing the digit if the conversion was successful or None if the conversion failed. You are matching:

  • Some(2), meaning a successful conversion resulting in the number 2, and
  • None, meaning an unsuccessful conversion.

The compiler is telling you, what about all successful conversions for any numbers other than 2? (Some(0u32..=1u32), (3u32..=std::u32::MAX)).

One way to solve this is using the underscore pattern, which matches anything. This way, you can match anything you are interested in, and then use _ as a fallback otherwise. For example:

match to_num {
    Some(2) => println!("matched"),
    _ => (),
}

However, in this situation, a simple "if" statement might be a better (more canonical) choice:

if to_num == Some(2) {
    println!("matched");
}
Related