3 ms·
> Rust's trait system does the heavy lifting for enabling this operator Are you sure? I thought that try! was a simple macro: https://doc.rust-lang.org/src/cor
by jashmatthews 8y ago
> Rust's trait system does the heavy lifting for enabling this operator
Are you sure? I thought that try! was a simple macro: https://doc.rust-lang.org/src/core/macros.rs.html#299 https://doc.rust-lang.org/src/core/macros.rs.html#299
- setr 8y ago?[1] is indeed based on traits and try! is a macro that depends on the trait system (line 303: $crate::convert::From::from(err)) to do the very important job of propagation and coercion, by means of error-wrapping. If all it could do was pass the error forward, it'd be quite annoying to deal with. Specifically that since rust represents errors with enums, and you have to handle every error, the eventual caller function would end up dealing with 10 different possible errors, defined in 10 different libraries, and has to be made aware of all downstream dependencies. Or you'd end up avoiding the operator altogether, and force the coercion in every instance, defeating the point of the operator. The ?/try! utilizes traits to instead allows you to auto-coerce them to a new error with a relevant message/trace (given the appropriate Into definition), allowing it to be a simple one-character addition with most of the expressive power of exceptions. The heavy lifting is specifically that coercion; the "continue or return" part isn't that significant (that would just be avoiding the any language one-liner: if err return err) [1] https://github.com/rust-lang/rfcs/blob/master/text/0243-trait-based-exception-handling.md https://github.com/rust-lang/rfcs/blob/master/text/0243-trai...
- masklinn 8y ago> The ?/try! utilizes traits to instead allows you to auto-coerce them to a new error with a relevant message/trace (given the appropriate Into definition), allowing it to be a simple one-character addition with most of the expressive power of exceptions. That is not a very important job, because it's a context-less conversion and thus only suitable for pretty basic conversions. > the "continue or return" part isn't that significant (that would just be avoiding the any language one-liner: if err return err) "continue or return" is by far the most important part of ?/try!, it reduces an extensive match into a single character or 6, making error handling both terse and simple for the common case where you just want to bubble up the error. Even if it did not do any conversion, such conversion is just a map_err away (and commonly necessary either way as the developer wants to add context or needs to convert from trait object or some such). The automatic conversion is a minor convenience.