How to use ok_or to convert Option to Result

Convert an Option to a Result in Rust using the ok_or method by providing a default error value for None cases.

Use the ok_or method on an Option to convert it into a Result, providing a specific error value for the None case. This method returns Ok if the option contains a value, or Err with your provided error if it is None.

let maybe_value: Option<i32> = Some(42);
let result: Result<i32, &str> = maybe_value.ok_or("No value found");

If maybe_value were None, result would be Err("No value found").