Rust 1.99 (2024 edition) reference · Option and Result
Rust Result::map_err, unwrap_or_else and ok Method
Convert or recover from errors: change the error type, fall back to a value, or discard the error as an Option.
Rust 1.99 (2024 edition)
Syntax
fn map_err<F>(self, op: O) -> Result<T, F> fn unwrap_or_else(self, op: F) -> T fn ok(self) -> Option<T>
Parameters
| Parameter | Description |
|---|---|
map_err |
Change the error, e.g. add context. |
map |
Change the Ok value. |
unwrap_or_else |
Recover with a function of the error. |
ok() |
Result to Option. |
is_ok / is_err |
Check without consuming. |
Examples
fn main() {
let r: Result<u16, String> = "70000".parse::<u16>().map_err(|e| format!("bad port: {e}"));
println!("{r:?}");
let port = "abc".parse::<u16>().unwrap_or_else(|_| 8080);
println!("{port}");
println!("{:?}", "12".parse::<u8>().ok());
}
Output
Err("bad port: number too large to fit in target type")
8080
Some(12)Run this on your computer — see “Get Started” for setup.
fn main() {
let inputs = ["1", "two", "3"];
let (ok, bad): (Vec<_>, Vec<_>) = inputs.iter().map(|s| s.parse::<i32>()).partition(|r| r.is_ok());
println!("{} ok, {} bad", ok.len(), bad.len());
let all: Result<Vec<i32>, _> = ["1", "2"].iter().map(|s| s.parse::<i32>()).collect();
println!("{all:?}");
}
Output
2 ok, 1 bad Ok([1, 2])
Run this on your computer — see “Get Started” for setup.
Related
The ? operator· Propagate errors from functions returning Result or Option: unwrap Ok values and return early on Err.Option::map, and_then and filter· Transform the value inside an Option without unwrapping it, chain optional steps, or keep it only if a condition holds.- Rust Result and the ? Operator · tutorial