This is kind of a tricky question to answer. I personally can't recall ever seeing anyone express this opinion before. To be fair, I can't say that I've ever heard the opposite. That is, I don't remember anyone ever explicitly encouraging this sort of pattern in code.
I've certainly used this pattern before, although somewhat sparingly. To demonstrate, this typically occurs when you have a match
expression with several cases in a tail expression that returns a Result
, and you don't want to write Ok
for each case. Like this:
Ok(match something {
Something::Foo => 1,
Something::Bar => 2,
Something::Quux => fallible?,
Something::Baz => return Err(...),
})
As opposed to
match something {
Something::Foo => Ok(1),
Something::Bar => Ok(2),
Something::Quux => fallible,
Something::Baz => Err(...),
}
It's not a huge difference, but if you have a lot of Ok
cases, it can get a bit annoying. Or at least, this was the primary complaint in Boat's blog post (in defense of Ok
-wrapping).
Another variant of this pattern is 1) when your function returns a Result
, 2) the tail expression of the function is also a Result
, 3) the error types are not the same and 4) the error type in (1) has a From
impl for the error type in (2). That is, instead of writing
something.fallible().map_err(From::from)
one can write
Ok(something.fallible()?)
?
is so ubiquitous that I've always kind of chalked up the difference between these to personal style.
I can't possibly know what the blog author had in mind when saying that this was poor form. My guess---and I somewhat share this---is that there is a lack of symmetry between the arms of the match
expression. Some of them are effectively early returns while others aren't early returns at all. I could see how some might consider that jarring.
Otherwise, I do occasionally use both of these patterns, but not religiously so. If it comes up and it makes sense, then I don't have too much of a problem with it.