Rust Fundamentals · 25 XP Pro
Parsing user input
Text from users, files or the network is untrusted, so turning it into numbers
is a job for Result. str::parse::<T>() returns Result<T, T::Err>, and you
choose T with a type annotation or the turbofish.
let a: Result<u32, _> = "17".parse();
let b = "x1".parse::<u32>(); // Err(ParseIntError)
Good input handling also trims whitespace, rejects empty input, and reports
which piece was wrong. You can turn a library error into your own message
with map_err:
let n: i32 = "q".parse().map_err(|_| "not a number".to_string())?;
Your task
This capstone combines the chapter. Everything must be pub, because the tests
use your crate as lesson.
pub fn parse_scores(line: &str) -> Result<Vec<u32>, String>reads comma-separated scores such as"10, 20,30". Trim each piece and parse it asu32.- A blank line (only whitespace) gives
Err("no scores".to_string()). - A bad piece gives
Err(format!("invalid score: {piece}")), wherepieceis the trimmed text, for exampleinvalid score: abc. Report the first bad one.
- A blank line (only whitespace) gives
pub fn average(line: &str) -> Result<f64, String>usesparse_scores(with?) and returns the mean as anf64, passing errors through unchanged.