liveBook · Manning

Ok_or

As explained in Learn Rust in a Month of Lunches

ok_or is a Rust Option method that converts Some to Ok and None to Err using a supplied error value.

ok_or converts an Option into a Result. Some(value) becomes Ok(value); None becomes Err(error), using the error value you provide. section 9.1.1

Use ok_or when a missing value should carry a specific error:

  • company.get_ceo().ok_or("No CEO found") turns each available CEO into Ok and each missing CEO into Err. section 9.1.1
  • The resulting type can be Result<String, &str>, producing values such as Ok("Unknown") and Err("No CEO found"). section 9.1.1
  • Use ok_or_else when creating the error requires a closure, such as formatting an error with the company name. section 9.1.1

Turning an optional CEO into a Result

let results: Vec<Result<String, &str>> = company_vec.iter().map(|company| company.get_ceo().ok_or("No CEO found")).collect(); section 9.1.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains the conversion and result values with a focused example, while deferring long-term custom error design.
Examples
Uses optional company CEOs, the error "No CEO found," and printed Ok and Err results.
What it assumes
Assumes familiarity with Option and Result, while defining how Some and None map to Ok and Err.
What you can do after
Apply via Rust’s standard library by assigning a meaningful Err value to a None case.
How it connects
Connects Option and Result with map, ok_or_else, and error handling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.