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
