std-method
Option::ok_or and ok_or_else
Convert absence into a meaningful error. ok_or computes the error argument eagerly, while ok_or_else builds it only when needed. Both consume Option. Expected stdout (not executed): Err("missing name") Common mistake: Expecting Option to already contain failure details.
Formal Syntax & Structure
rust syntaxrust
fn ok_or<E>(self, err: E) -> Result<T,E>; fn ok_or_else<E,F: FnOnce() -> E>(self, err: F) -> Result<T,E>Working Example
Example Snippetrust
fn main() { let name: Option<&str> = None; println!("{:?}", name.ok_or("missing name"));}