Result is_ok_and And is_err_and
Result::is_ok_and evaluates a predicate only when Ok and is_err_and only when Err, letting callers branch on outcomes without unwrapping.
Code
fn main() {
let loaded: Result<Vec<String>, String> = Ok(vec!["a".into(), "b".into()]);
// is_ok_and:只在 Ok 时评估谓词,Err 直接返回 false
let usable = loaded.is_ok_and(|items| items.len() > 1);
println!("usable: {usable}");
let failed: Result<u16, String> = Err("connection refused".into());
// is_err_and:只在 Err 时评估谓词,Ok 直接返回 false
let retryable = failed.is_err_and(|e| e.contains("refused"));
println!("retryable: {retryable}");
// 借用检查:as_ref 让谓词拿引用,loaded 之后还能继续用
let has_a = loaded.as_ref().is_ok_and(|items| items.iter().any(|i| i == "a"));
println!("has a: {has_a}");
}Inside the snippet
One way to read it: the function main, doing all the work.
Result is the error channel: the caller receives the failure as a value instead of an exception.
Caveats
- The toolchain alone is enough — no dependency resolution happens.
Resultis the only error channel — remove a?while adapting and that site needs an explicitmatch.
Putting it to use
Its full declaration is fn main()
Output lines are prefixed (usable:, retryable:, has a:), making each step’s effect easy to spot.
Core lines
let has_a = loaded.as_ref().is_ok_and(|items| items.iter().any(|i| i == "a"));
let loaded: Result<Vec<String>, String> = Ok(vec!["a".into(), "b".into()]);
let failed: Result<u16, String> = Err("connection refused".into());
Interactive Tools for This Topic
FAQ
- How do errors reach the caller?
- Through the type system: failures are `Result` variants the caller must consume.
- What does Result is_ok_and And is_err_and print when run?
- Execute the whole file; each printed line is prefixed with a label like `usable:`, `retryable:`, `has a:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.