jakub_neruda, Czech
@jakub_neruda@techhub.social avatar

Tip 40 of #TuesdayCodingTips - Rust's error propagation is amazing

As much as I love C++, its optional and expected objects can just envy one killer feature of their Rust counterparts. If you're working with a Result<T, E> in a function that returns a Result<U, E2>, you can use operator ? to simply unwrap the Ok value into a variable. If the result contains an error, Rust will not panic; rather, it returns that error from the current function similar to how exception would bubble up the code. The only limitation is that the function must return Result with the error type to which the propagated error can be implicitly converted.

Option also supports the operator ?, which either propagates None up the call stack or safely unwraps the stored Some.

I'd kill to have this in C++, where you would have to employ non-standard compiler extensions to create a macro that would be at least close.

#rust #programming #tips

  • All
  • Subscribed
  • Moderated
  • Favorites
  • rust
  • ngwrru68w68
  • rosin
  • GTA5RPClips
  • osvaldo12
  • love
  • Youngstown
  • slotface
  • khanakhh
  • everett
  • kavyap
  • mdbf
  • DreamBathrooms
  • thenastyranch
  • magazineikmin
  • megavids
  • InstantRegret
  • normalnudes
  • tacticalgear
  • cubers
  • ethstaker
  • modclub
  • cisconetworking
  • Durango
  • anitta
  • Leos
  • tester
  • provamag3
  • JUstTest
  • All magazines