Result Flatten Unwraps Nested Outcomes

Collapse Result<Result<T,E>,E> into a single layer with flatten, keeping only the outer error when the wrapper itself failed.

RustData Integrity

Code

rustsnippet
23 lines
fn parse_pair(raw: &str) -> Result<i32, String> {
    raw.parse::<i32>().map_err(|e| format!("not a number: {e}"))
}

fn main() {
    let inputs = ["42", "x1", "99"];

    for raw in inputs {
        // 先 map 得到两层 Result:外层代表"行存在",内层代表"值可解析"
        let nested: Result<Result<i32, String>, String> = if raw.is_empty() {
            Err("empty row".into())
        } else {
            Ok(parse_pair(raw))
        };

        // flatten 折成一层:外层失败时保留外层错误
        let flat = nested.flatten();
        match flat {
            Ok(n) => println!("{raw:?} -> {n}"),
            Err(e) => println!("{raw:?} -> error: {e}"),
        }
    }
}

Inside the snippet

Result Flatten Unwraps Nested Outcomes is built around the functions parse_pair and main.

One loop does the cycling here: for raw in inputs. Failure is encoded in the return type — Result leaves no room for an unhandled error. match here is the control flow: arms enumerate the value’s shapes exhaustively.

Caveats

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.
  • Every fallible call yields a Result you must unwrap or propagate; there is no implicit throw.

Putting it to use

Entry signature: fn parse_pair(raw: &str) -> Result<i32, String>

Treat main as the orchestrator calling parse_pair in a fixed order.

Core lines

fn parse_pair(raw: &str) -> Result<i32, String> {
    raw.parse::<i32>().map_err(|e| format!("not a number: {e}"))
}
match flat {
    Ok(n) => println!("{raw:?} -> {n}"),
    Err(e) => println!("{raw:?} -> error: {e}"),
}
Err("empty row".into())
} else {
Ok(parse_pair(raw))
};

Interactive Tools for This Topic

FAQ

What happens when a call fails?
Through `Result` values. Nothing panics inside the snippet; the caller decides how to handle each failure.
How do you run Result Flatten Unwraps Nested Outcomes?
Run the file on its own; every call resolves against the standard surface it already imports.