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.

  1. 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 as u32.
    • A blank line (only whitespace) gives Err("no scores".to_string()).
    • A bad piece gives Err(format!("invalid score: {piece}")), where piece is the trimmed text, for example invalid score: abc. Report the first bad one.
  2. pub fn average(line: &str) -> Result<f64, String> uses parse_scores (with ?) and returns the mean as an f64, passing errors through unchanged.

Next lesson →

Sign in to run your code. It's free.