error-concept

anyhow::with_context: lazy context

Build a message only when a result fails. Useful when formatting a synthetic record identifier or calculating diagnostic details. Requires anyhow = "=1.0.104" in Cargo.toml. See the staged dependency project. Expected stdout (not executed): ok=true calls=0 Expected stderr: (empty) Expected exit: success Common mistake: Performing required side effects inside the closure; success skips it.

Formal Syntax & Structure

rust syntaxrust
result.with_context(|| message)?

Working Example

Example Snippetrust
use anyhow::Context;fn main() {    let mut calls = 0;    let value = "12".parse::<u32>().with_context(|| {        calls += 1;        String::from("parse record 7")    });    println!("ok={} calls={calls}", value.is_ok());}
Rust Reference