Home > Back-end >  force error when parsing "01" from string to number in rust
force error when parsing "01" from string to number in rust

Time:11-11

I've have a string like this

"32" or "28", "01", "001"

and I want to parse them to a number. However it should not parse a string that starts with 0.

Currently, I'm doing this

let num = str.parse().unwrap_or(-1);

With this implementation it converts "01" to 1 but I want to force -1 when the string stars with 0.

CodePudding user response:

As mentioned in the comments - you could use this:

let num = if s.starts_with('0') {
    -1
} else {
    s.parse().unwrap_or(-1)
};
  • Related