Transpose Bridges Options And Results
transpose swaps Option and Result nesting so errors surface outward, and flatten unwraps one layer of wrapped Results after the swap.
Code
fn main() {
// Option<Result<T, E>> → Result<Option<T>, E>:错误外提,成功时保留缺失语义
let present: Option<Result<i32, String>> = Some(Ok(7));
let missing: Option<Result<i32, String>> = None;
let failed: Option<Result<i32, String>> = Some(Err("bad digit".into()));
println!("{:?}", present.transpose()); // Ok(Some(7))
println!("{:?}", missing.transpose()); // Ok(None)
println!("{:?}", failed.transpose()); // Err("bad digit")
// 反方向:Result<Option<T>, E> → Option<Result<T, E>>
let ok_some: Result<Option<i32>, String> = Ok(Some(3));
println!("{:?}", ok_some.transpose()); // Some(Ok(3))
// 嵌套包装展平一层:Result<Result<i32, E>, E> → Result<i32, E>
let nested: Result<Result<i32, String>, String> = Ok(Ok(9));
println!("{:?}", nested.flatten()); // Ok(9)
// 实战:可选配置解析——None 给 Ok(None),Some 里的解析错误向上传播
let raw: Option<&str> = Some("42");
let parsed = raw.map(|s| s.parse::<i32>()).transpose();
println!("{:?}", parsed); // Ok(Some(42))
}What the code does
Transpose Bridges Options And Results comes down to the function main.
Fallible operations return Result, forcing the caller to handle both arms explicitly.
Points of care
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Statements that matter
let failed: Option<Result<i32, String>> = Some(Err("bad digit".into()));
let present: Option<Result<i32, String>> = Some(Ok(7));
let ok_some: Result<Option<i32>, String> = Ok(Some(3));
Interactive Tools for This Topic
FAQ
- How should callers handle failures?
- As `Result` values — each fallible call returns one, and the caller matches or propagates it.
- How do you run Transpose Bridges Options And Results?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.