rust-unofficial / patterns

A catalogue of Rust design patterns, anti-patterns and idioms
https://rust-unofficial.github.io/patterns/
Mozilla Public License 2.0
7.85k stars 354 forks source link

Add fallible closure to idioms #250

Open jRimbault opened 3 years ago

jRimbault commented 3 years ago

This is a short idiom I think I've seen several times.

Using a fallible closure inside an infallible function to allow the use of the ? operator.

simonsan commented 3 years ago

@jRimbault Do you still want to add anything or is it ready to review?

jRimbault commented 3 years ago

I think it would be good to elaborate a bit more and give a better example, but yes I'm ready to review and change things if needed ?

jRimbault commented 3 years ago

This was prompted by someone on reddit asking how to write the first two functions, to which I replied with the 3rd implementation. I think I've seen that idiom here and there in Rust code.

simonsan commented 3 years ago

The general question is also when you should do it and when not. I mean it's obviously pretty bad for error handling and I would consider it kind of an anti-pattern somehow in this regards, as also mentioned in the # Disadvantages. Also it's quite unclear (for me as a reader) why you would use try/? to bubble up errors, but then don't handle them. Maybe to just sketch out/hack something fastly? I think in this regards the text could elaborate a bit more, imho.

jRimbault commented 3 years ago

I'll sleep on on your advice (it's 11pm in my timezone). I think I should first find some good examples (of good* and bad use cases). I've only had one legit use case. It's often came up when trying to help someone else though. IMO this should definitely not be in a function in a public API. It's really about syntax convenience when the author thinks they have a good default case.

simonsan commented 6 months ago

Any updates on this? 🚀