Ok Or Bridges Options Into Results

Convert Option into Result with ok_or so the question-mark operator can propagate a missing value, and reach for ok_or_else to build errors lazily.

RustData Integrity

Code

rustsnippet
20 lines
fn port_from(raw: Option<&str>) -> Result<u16, String> {
    // ok_or:None 变成具体错误后交给 ? 传播,Some 原样放行
    let text = raw.ok_or("port missing from config")?;
    text.parse::<u16>()
        .map_err(|e| format!("port {text:?} invalid: {e}"))
}

fn main() {
    for raw in [Some("8080"), Some("99999"), None] {
        match port_from(raw) {
            Ok(port) => println!("port {port} ok"),
            Err(reason) => println!("rejected: {reason}"),
        }
    }

    // ok_or_else:闭包只在 None 时才构造错误,昂贵的错误构造用这个
    let name: Option<String> = None;
    let label = name.ok_or_else(|| "name not provided".to_string());
    println!("label: {:?}", label.unwrap_err());
}

How it works

Ok Or Bridges Options Into Results is built around the functions port_from and main.

for raw in [Some("8080"), Some("99999"), None] is the loop that carries the per-item work. Result is the error channel: the caller receives the failure as a value instead of an exception. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

Caveats

  • Result is the only error channel — remove a ? while adapting and that site needs an explicit match.

Putting it to use

The main signature reads fn port_from(raw: Option<&str>) -> Result<u16, String>

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

main calls 1 helper in sequence: port_from.

Core lines

for raw in [Some("8080"), Some("99999"), None] {
match port_from(raw) {
Ok(port) => println!("port {port} ok"),
Err(reason) => println!("rejected: {reason}"),
}
}
fn port_from(raw: Option<&str>) -> Result<u16, String> {
// ok_or:None 变成具体错误后交给 ? 传播,Some 原样放行
let text = raw.ok_or("port missing from config")?;
text.parse::<u16>()
.map_err(|e| format!("port {text:?} invalid: {e}"))
}
let name: Option<String> = None;

Interactive Tools for This Topic

FAQ

Is there exception handling?
No panics — `Result` values carry the failure, and `?` forwards them to the caller.
What does Ok Or Bridges Options Into Results print when run?
Run it as a complete program — the output lines carry labels such as `port`, `rejected:`, `label:`.