Option And Result Inspect Ok Branches
Option::inspect and Result::inspect run a closure on the Some or Ok value only, leaving the value untouched and doing nothing for None or Err.
Code
fn audit(note: &str) {
println!("[audit] {note}");
}
fn main() {
// Option::inspect runs the closure only on the Some branch, passing a shared reference
let config: Option<u16> = Some(8080);
let kept = config.inspect(|port| audit(&format!("port {port}")));
println!("kept: {kept:?}");
// None passes through untouched: the closure never runs
let absent: Option<u16> = None;
let unchanged = absent.inspect(|port| audit(&format!("port {port}")));
println!("unchanged: {unchanged:?}");
// Result::inspect observes the Ok value: the Err side flows through unchanged for inspect_err to handle
let parsed: Result<u16, String> = Ok(443);
let verified = parsed.inspect(|port| audit(&format!("bind {port}")));
println!("verified: {verified:?}");
}Inside the snippet
Everything happens inside the functions audit and main.
Fallible operations return Result, forcing the caller to handle both arms explicitly.
What to watch for
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Using it
Entry signature: fn audit(note: &str)
The demo output is labeled ([audit], kept:, unchanged:); each label names the call that printed it.
Start the program and main runs audit one after another.
Statements that do the lifting
let parsed: Result<u16, String> = Ok(443);
let config: Option<u16> = Some(8080);
let absent: Option<u16> = None;
Interactive Tools for This Topic
FAQ
- What is the error handling style?
- Through `Result` values. Nothing panics inside the snippet; the caller decides how to handle each failure.
- What does Option And Result Inspect Ok Branches print when run?
- Running the file directly is enough — expect labeled output lines such as `[audit]`, `kept:`, `unchanged:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.