Result Constructors And Collect Vec

Build Results with Ok and Err, lift fallible steps into one pipeline, and collect into Result<Vec, E> so any failure sinks the batch.

RustData Integrity

Code

rustsnippet
35 lines
fn parse_station(raw: &str) -> Result<(String, f64), String> {
    // split_once 找到首个分隔符:左右两侧分开处理
    let (name, value) = raw
        .split_once('=')
        .ok_or_else(|| format!("missing '=' in {raw:?}"))?;
    let temperature = value
        .trim()
        .parse::<f64>()
        .map_err(|e| format!("bad temperature in {raw:?}: {e}"))?;
    if !(-90.0..=60.0).contains(&temperature) {
        return Err(format!("temperature {temperature} out of range"));
    }
    Ok((name.trim().to_string(), temperature))
}

fn main() {
    let rows = ["oslo=4.5", "tokyo=18.2", "lima=22.0"];

    // collect 到 Result<Vec<_>, String>:全部成功才得到整批数据
    let stations: Result<Vec<(String, f64)>, String> =
        rows.iter().map(|r| parse_station(r)).collect();
    match stations {
        Ok(list) => {
            let avg = list.iter().map(|(_, t)| t).sum::<f64>() / list.len() as f64;
            println!("{} stations, avg {avg:.1}", list.len());
        }
        Err(e) => println!("rejected batch: {e}"),
    }

    // 一条坏记录短路整批:首个 Err 胜出
    let broken = ["oslo=4.5", "paris=not-a-number"];
    let attempt: Result<Vec<(String, f64)>, String> =
        broken.iter().map(|r| parse_station(r)).collect();
    println!("attempt: {}", attempt.is_err());
}

How it works

Result Constructors And Collect Vec comes down to the functions parse_station and main.

Fallible operations return Result, and the ? operator short-circuits errors up to the caller. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Using it

Signature: fn parse_station(raw: &str) -> Result<(String, f64), String>

Running the file prints labeled results such as rejected batch:, attempt: — each operation’s effect is visible in the output.

Running the file executes main, which drives parse_station in order.

Key statements

broken.iter().map(|r| parse_station(r)).collect();
rows.iter().map(|r| parse_station(r)).collect();
let avg = list.iter().map(|(_, t)| t).sum::<f64>() / list.len() as f64;

Interactive Tools for This Topic

FAQ

How does the code signal failure?
As data, not exceptions: `Result` makes the caller handle both arms.
What does Result Constructors And Collect Vec print when run?
Invoke the file as-is — the `rejected batch:`, `attempt:` prefixes identify which step printed each line.