Error Handling Patterns
Option to Result
Adding an Error Message
Option says a value may be absent. ok_or turns absence into a Result with an explicit error value.
Program
Play the program to look up a selected setting and label missing keys.
option_to_result.rs
fn lookup(key: &str) -> Result<&'static str, &'static str> {
let value = match key {
"host" => Some("local"),
"port" => Some("8080"),
_ => None,
};
value.ok_or("missing")
}
fn main() {
let key = ;
let result = lookup(key);
let label = match result {
Ok(value) => format!("{key}={value}"),
Err(error) => format!("{key}:{error}"),
};
println!("{label}");
}
fn lookup(key: &str) -> Result<&'static str, &'static str> {
let value = match key {
"host" => Some("local"),
"port" => Some("8080"),
_ => None,
};
value.ok_or("missing")
}
fn main() {
let key = ;
let result = lookup(key);
let label = match result {
Ok(value) => format!("{key}={value}"),
Err(error) => format!("{key}:{error}"),
};
println!("{label}");
}
fn lookup(key: &str) -> Result<&'static str, &'static str> {
let value = match key {
"host" => Some("local"),
"port" => Some("8080"),
_ => None,
};
value.ok_or("missing")
}
fn main() {
let key = ;
let result = lookup(key);
let label = match result {
Ok(value) => format!("{key}={value}"),
Err(error) => format!("{key}:{error}"),
};
println!("{label}");
}
Option
`Option<T>` is either `Some(T)` or `None`.
ok_or
`ok_or(error)` turns `Some` into `Ok` and `None` into `Err(error)`.
lookup result
The caller gets a `Result` with a clear missing-key label.