Open Nemo157 opened 5 years ago
I found transpose
useful when I am creating an Option<T>
within a function that returns some Result<..>
because it lets you use ?
. An example is illustrative:
struct Foo {
x: Option<u64>,
}
// with transpose
fn parse_foo(x: &str) -> Result<Foo> {
Ok(Foo { x: x.strip_prefix("z").map(|a| a.parse()).transpose()? })
}
/// without transpose
fn parse_foo2(x: &str) -> Result<Foo> {
Ok(Foo {
x: match x.strip_prefix("z") {
Some(x) => Some(x.parse()?),
None => None,
},
})
}
A match statement with None => None
and where the Some
branch uses ?
would likely be a good candidate to be rewritten as .map(...).transpose()?
.
This github search shows tons of examples (and many more that could just use regular old Option::map
)
https://github.com/search?q=language%3Arust+%22None+%3D%3E+None%22&type=code
This issue has an async/await tag but it does not relate to async/await. Just iterables.
The loop in
main
could instead be writtenI don't know how easy this would be to detect, and because of
for
loops it is not that widely applicable, but IMO it does lead to an appreciable increase in code readability.One upcoming usecase where this will come up a lot is working with async
Stream
s, those will commonly be streams of results and can't be used withfor
loops, so the standard way to work with them should be