Fallible
Fallible
is an Option
with inverted Try
-semantics.
What this means is that using the ?
operator on a Fallible<E>
will exit early
if an error E
is contained within, or instead act as a no-op, if the value is Success
.
This is in contrast to Option
where using ?
on a None
-value will exit early.
Fallible
fills the gap left by the Result
and Option
types:
Potential Success | Potential Failure |
---|---|
Result<T |
, E> |
Option<T> |
Fallible<E> |
Example
This code illustrates how Fallible
can be used to write succint
validation code which exits early in case of failure.
use ;
// Validates the input number `n`, returning a `Fail`
// if the input number is zero, or `Success` otherwise.
;
// Check many numbers, returning early if a tested
// number is equal to zero.
assert_eq!;
Motivation
Fallible
fills the gap left by Option
and Result
and clearly conveys intent and potential outcomes of a function.
A function which returns Fallible
has only two potential outcomes, it can fail with an error E
, or it can succeed.
Why not Result
?
Because Result
implies output. Take std::fs::rename
for instance:
If I told you that the return type of rename
was a Result<T, E>
, what would you guess T
and E
to be?
You might rightly assume that E
was std::io::Error
, but what about T
? It could reasonably return any number of things:
- The canonical path of the destination of the renamed file.
- The size of the moved file.
- The size of the file (if any) replaced by the renamed file.
- Or perhaps even a handle to the overwritten file.
Of course none of these are true, as the T
value of rename
is the unit value ()
. rename
never
produces any output, it can only signal errors. So why not signal that clearly to the user?
I would argue that using a type which signals the potential for failure, but no output upon success would more clearly express the intent and potential outcomes when using this function.
Why not Option
?
Potential failure could be expressed using an Option<E>
, but as stated above, the Try
-semantics
of Option
makes it unergonomic to work with:
type Error = &'static str;
;
Conversion from Result
Switching from using Result
to Fallible
is very simple, as illustrated with this before/after example:
Using Fallible
:
Compatibility
Fallible
contains utility functions for mapping to and from [Result
] and [Option
],
as well as [FromResidual
] implementations for automatically performing these conversions
when used with the ?
operator.