Reputation: 73
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.
Upvotes: -1
Views: 378
Reputation: 30577
As mentioned in the comments - you could use this:
let num = if s.len() > 1 && s.starts_with('0') {
-1
} else {
s.parse().unwrap_or(-1)
};
Upvotes: 1