236. Result::flatten — Collapse a Result<Result<T, E>, E> in One Call
Ended up with a Result<Result<T, E>, E> and reached for a nested match to peel it? When both layers share the same error type, Result::flatten (stable since 1.89) does it in one call.
How you get a doubly-wrapped Result
It usually sneaks in when you map a fallible operation over something that’s already a Result:
| |
The outer Result is “did we have a line?”, the inner one is “did it parse?”. Same String error on both — but the type is now Result<Result<u32, String>, String>, which no caller wants to touch.
The manual peel
| |
Correct, but it’s boilerplate that hides the intent.
flatten does exactly this
| |
Ok(Ok(x)) becomes Ok(x); either Err — inner or outer — passes straight through. Option has the same method, Option::flatten, for Option<Option<T>>.
The catch: error types must match
flatten is Result<Result<T, E>, E> → Result<T, E> — one E. If the two layers carry different error types, flatten can’t merge them. Reach for and_then instead, which lets ?-style conversion do the work:
| |
When the errors already line up, flatten is the clearest way to say “unwrap one layer of nesting.”