Trait Try
trait Try: ~const FromResidual
The ? operator and try {} blocks.
try_* methods typically involve a type implementing this trait. For
example, the closures passed to Iterator::try_fold and
Iterator::try_for_each must return such a type.
Try types are typically those containing two or more categories of values,
some subset of which are so commonly handled via early returns that it's
worth providing a terse (but still visible) syntax to make that easy.
This is most often seen for error handling with Result and Option.
The quintessential implementation of this trait is on ControlFlow.
Using Try in Generic Code
Iterator::try_fold was stabilized to call back in Rust 1.27, but
this trait is much newer. To illustrate the various associated types and
methods, let's implement our own version.
As a reminder, an infallible version of a fold looks something like this:
So instead of f returning just an A, we'll need it to return some other
type that produces an A in the "don't short circuit" path. Conveniently,
that's also the type we need to return from the function.
Let's add a new generic parameter R for that type, and bound it to the
output type that we want:
#
# use Try;
If we get through the entire iterator, we need to wrap up the accumulator
into the return type using [Try::from_output]:
#
# use ;
We'll also need FromResidual::from_residual to turn the residual back
into the original type. But because it's a supertrait of Try, we don't
need to mention it in the bounds. All types which implement Try can be
recreated from their corresponding residual, so we'll just call it:
#
# use ;
But this "call branch, then match on it, and return if it was a
Break" is exactly what happens inside the ? operator. So rather than
do all this manually, we can just use ? instead:
#
# use Try;
Associated Types
type OutputThe type of the value produced by
?when not short-circuiting.type ResidualThe type of the value passed to
FromResidual::from_residualas part of?when short-circuiting.This represents the possible values of the
Selftype which are not represented by theOutputtype.Note to Implementors
The choice of this type is critical to interconversion. Unlike the
Outputtype, which will often be a raw generic type, this type is typically a newtype of some sort to "color" the type so that it's distinguishable from the residuals of other types.This is why
Result<T, E>::Residualis notE, butResult<Infallible, E>. That way it's distinct fromControlFlow<E>::Residual, for example, and thus?onControlFlowcannot be used in a method returningResult.If you're making a generic type
Foo<T>that implementsTry<Output = T>, then typically you can useFoo<std::convert::Infallible>as itsResidualtype: that type will have a "hole" in the correct place, and will maintain the "foo-ness" of the residual so other types need to opt-in to interconversion.
Required Methods
fn from_output(output: <Self as >::Output) -> SelfConstructs the type from its
Outputtype.This should be implemented consistently with the
branchmethod such that applying the?operator will get back the original value:Try::from_output(x).branch() --> ControlFlow::Continue(x).Examples
use Try; assert_eq!; assert_eq!; assert_eq!; # # make_question_mark_work; // This is used, for example, on the accumulator in `try_fold`: let r = empty.try_fold; assert_eq!;fn branch(self: Self) -> ControlFlow<<Self as >::Residual, <Self as >::Output>Used in
?to decide whether the operator should produce a value (because this returnedControlFlow::Continue) or propagate a value back to the caller (because this returnedControlFlow::Break).Examples
use ; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;