Parse A Number List From A String

Split a string, trim whitespace, and parse each field into numbers, keeping valid values and reporting the fields that failed.

RustData Integrity

Code

rustsnippet
29 lines
fn parse_measurements(input: &str) -> (Vec<f64>, Vec<String>) {
    let mut ok = Vec::new();
    let mut bad = Vec::new();
    for field in input.split(',') {
        match field.trim().parse::<f64>() {
            // trim 掉首尾空白后再 parse,容忍 " 12 "
            Ok(n) => ok.push(n),
            Err(_) => bad.push(field.trim().to_string()),
        }
    }
    (ok, bad)
}

fn main() {
    let raw = "12.5,  8, bad, 3.25 , , 42";
    let (values, failed) = parse_measurements(raw);
    println!("parsed: {values:?}");
    println!("failed: {failed:?}");
    println!("sum of parsed: {}", values.iter().sum::<f64>());

    // 全部合法时 collect 直接得到 Vec,遇到非法项整体失败
    let strict: Result<Vec<i32>, _> =
        "1,2,3".split(',').map(str::trim).map(str::parse).collect();
    println!("strict ok: {strict:?}");

    let strict_fail: Result<Vec<i32>, _> =
        "1,x,3".split(',').map(str::trim).map(str::parse).collect();
    println!("strict fail: {strict_fail:?}");
}

How the snippet works

All of the logic lives in the functions parse_measurements and main.

The file repeats itself only inside for field in input.split(','). Result is the error channel: the caller receives the failure as a value instead of an exception. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Watch out for

  • Copy, run: the standard library answers every call in the file.
  • Result is the only error channel — remove a ? while adapting and that site needs an explicit match.

Using it

The primary signature is fn parse_measurements(input: &str) -> (Vec<f64>, Vec<String>)

The demo output is labeled (parsed:, failed:, sum of parsed:); each label names the call that printed it.

The sequence parse_measurements lives in main; running the file triggers it.

Key statements

"1,2,3".split(',').map(str::trim).map(str::parse).collect();
"1,x,3".split(',').map(str::trim).map(str::parse).collect();
match field.trim().parse::<f64>() {
    // trim 掉首尾空白后再 parse,容忍 " 12 "
    Ok(n) => ok.push(n),
    Err(_) => bad.push(field.trim().to_string()),
}

Interactive Tools for This Topic

FAQ

Is there exception handling?
As data, not exceptions: `Result` makes the caller handle both arms.
What does Parse A Number List From A String print when run?
The script runs standalone; its 5 labeled outputs include `parsed:`, `failed:`, `sum of parsed:`.