I currently have code that takes 1 or 2 number inputs from the CLI.
Currently I have to write them as: 123456789
But I also want to write them as : 1_234_456_789
How do you do that in Rust?
Here's my Rust code:
let mut val = String::new(); // Inputs are 1 or 2 range values < 2**64
std::io::stdin().read_line(&mut val).expect("Failed to read line");
let mut substr_iter = val.split_whitespace();
let mut next_or_default = |def| -> usize {
substr_iter.next().unwrap_or(def).parse().expect("Input is not a number")
};
let mut end_num = std::cmp::max(next_or_default("3"), 3); // min vals 3
let mut start_num = std::cmp::max(next_or_default("3"), 3);
For comparison, here's how to read the underscores in Crystal:
Like this, maybe? You only need to change the call in your next_or_default closure and add a replace('_', "") before parse():
fn main() {
let val = "123_456_789 1_000_000";
let mut substr_iter = val.split_whitespace();
let mut next_or_default = |def| -> usize {
substr_iter.next().unwrap_or(def).replace('_', "").parse().expect("Input is not a number")
};
assert_eq!(next_or_default("3"), 123_456_789);
assert_eq!(next_or_default("3"), 1_000_000);
assert_eq!(next_or_default("3"), 3);
}