Hey! I am new here in the community and in Rust, and I was wondering how you would rewrite my code in an idiomatic way :
use std::io;
#[derive(Debug)]
pub enum Input {
// numbers
Number(u32),
// Break when user type `/`
Break,
Error,
}
impl Input {
/*
*/
pub fn from(answer: String) -> Self {
if answer.trim() == "/".to_string() {
return Self::Break;
}
match answer.trim().parse::<u32>() {
Ok(num) => Self::Number(num),
Err(_) => Self::Error,
}
}
}
pub fn ask_numbers() -> Vec<u32> {
// storing numbers
let mut list = Vec::new();
loop {
println!("Enter u32 and enter `/` to end the list");
let mut answer = String::new();
io::stdin()
.read_line(&mut answer)
.expect("Failed to read input");
let input = Input::from(answer);
match input {
Input::Number(num) => list.push(num),
Input::Break => break,
Input::Error => continue,
};
}
list
}
What I am trying to do here is asking the user to enter a list of numbers to be stored in a vector.
If the user enters something else than a number, they will get an error. and asked to enter a number again.
In order for the loop to end, the user will have to enter /
to break the loop.
It has only been 3 days that I am learning Rust so I don't have much of resources to help myself, so if you have any advices, links (youtube channels, etc... other than "the book") to learn Rust, I'll be glad to get them
Thanks in advance,
Noah