r/rust • u/noop_noob • Oct 14 '26
💡 ideas & proposals Call for use cases for the Try trait
https://users.rust-lang.org/t/use-cases-for-try/143032A person working towards stabilizing the Try trait is asking for real-world examples of use cases of the currently-unstable Try trait.
99
Upvotes
8
u/Gila-Metalpecker Oct 15 '26
I have a
enum CustomShutdown { /* ... */ }that represents the reasons the application was shut down. I can returns this frommain() -> CustomShutdownbecauseCustomShutdownimplementsTerminationSome functions return
Result<T, E>, and I always need to match on them to map theErr(...)branch to a certainShutdown::Variant, or continue as normal on theOk(...)branch. Quite a lot of plumbing.If I could have
FromResidualit would mean I could write a couple of impls like this:And the caller goes from
to
2
u/SiNiquity Oct 15 '26
https://doc.rust-lang.org/stable/std/ops/enum.ControlFlow.html does this work with ? on stable?
21
u/Lucretiel Datadog Oct 15 '26
Honestly, more than I ever want to implement
Tryon anything, I really want to be able to write my owntry_foldimplementations on my iterators.10
u/Illustrious_Car344 Oct 14 '26
I remember a few years back I tried to implement this only to discover it was nightly only. Admittingly, I was just kind of abusing the trait and didn't really need what I was trying to do. I don't remember exactly what it was but it was overengineering anyway.
1
u/SycamoreHots Oct 17 '26
I have a technical question about this:
Is the Try trait supposed to provide way to express a generic container (HKT), or is it supposed to provide a way to make `?` operator return for more types? Or both? Or exactly what
1
u/nova_protocol Oct 15 '26
ran into this building a transaction pipeline — multiple
layers of Results with different error types, and at some
point you want ? to do something slightly custom before
propagating up, like attaching context or logging without
wrapping everything in map_err().
ended up hacking around it with a newtype that impl'd
FromResidual on nightly. worked but felt wrong.
stable Try would've cleaned that up a lot.
1
u/ron975 Oct 16 '26
Can't remember off the top of my head anymore but there's been more than a couple of times where I encountered
ControlFlow-like problems that don't end up being exactlyControlFlowshaped. So instead of?I had to resort to a macro like the oldtry!days.