I'm new to Rust and I'm working through the exercises found at the bottom of this page. The following code parses a space deliminated input string from the user into a Vec<i16>
. If the input string is invalid, the code loops and prompts again. If the string is valid, it prints out the debug value of the Vec<i16>
and prompts again.
The code works, but I feel there is a more idomatic Rust way to deal with this. Particularly, in the get_input
function's looping and how its assigning the return value. Behold.
use std::io::Write;
fn main() {
while let Some(ary) = get_input() {
println!("{:?}", ary);
}
println!("Peace!");
}
fn get_input() -> Option<Vec<i16>> {
let mut out: Option<Vec<i16>> = None;
let mut valid = false;
while !valid {
// Get user input.
print!("Enter series-> ");
std::io::stdout().flush().unwrap();
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
// Parse it.
match input.trim() {
"q" => {
valid = true;
out = None;
}
_ => {
let parsed = parse_input(input);
if let Ok(_) = parsed {
out = Some(parsed.unwrap());
valid = true;
}
}
}
}
out
}
fn parse_input(input: String) -> Result<Vec<i16>, std::num::ParseIntError> {
input
.split_whitespace()
.map(|token| token.parse::<i16>())
.collect::<Result<Vec<i16>, _>>()
}