#![feature(try_blocks)]
pub fn is_valid(code: &str) -> bool {
let result: Result<bool, ()> = try {
code.chars()
.filter(|x| !x.is_whitespace())
.map(|x| x.to_digit(10).unwrap())
.rev()
.enumerate()
.map(|(i, num)| match i % 2 != 0 {
true => {
let doubled = 2 * num;
match doubled > 9 {
true => doubled - 9,
false => doubled,
}
}
false => num,
})
.sum::<u32>()
% 10
== 0
};
match result {
Ok(value) => value,
Err(_) => false,
}
}
On some inputs, this programme panics, and I don't understand why. The to_digit returns an Option, but it is unwrapped, and the None case should be caught by the try block. My understanding is that if the .unwrap is called on a None value, the try block will return a Result::Error, which the final match will convert into false.
I am new to Rust!
I did try x.to_digit(10).ok_or("Error").unwrap() to turn it into a Result rather than an Option, but it didn't make any difference.