Match Nested Result And Option Layers
Unwrap Result Option pairs in one match: Ok Some yields the value, Ok None means a missing record, and Err carries the query failure.
Code
fn main() {
// Result<Option<i32>, String>:查询成功与否 × 记录是否存在,两层嵌套
let rows = vec![
Ok(Some(42)),
Ok(None), // 查询成功但记录不存在
Err("db offline".to_string()), // 查询本身失败
];
// 一条 match 同时拆两层,无需中间变量或 transpose
for row in &rows {
match row {
Ok(Some(value)) => println!("value: {value}"),
Ok(None) => println!("missing row"),
Err(err) => println!("query failed: {err}"),
}
}
// 对照:手写两层 match 等价但啰嗦
let nested = match rows[0] {
Ok(inner) => match inner {
Some(v) => v * 2,
None => 0,
},
Err(_) => -1,
};
println!("nested: {nested}");
}What the code does
Match Nested Result And Option Layers is built around the function main.
Repetition is confined to for row in &rows — the rest of the file is straight-line. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.
Using it
Running the file prints labeled results such as value:, missing row, query failed: — each operation’s effect is visible in the output.
Key statements
Ok(inner) => match inner {
Some(v) => v * 2,
None => 0,
},
Ok(None), // 查询成功但记录不存在
Err("db offline".to_string()), // 查询本身失败
];
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Match Nested Result And Option Layers print when run?
- The script runs standalone; its 4 labeled outputs include `value:`, `missing row`, `query failed:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.