The inner! macro makes descending into an enum variant
more ergonomic. The some! and ok! macros turns an enum
into an Option or Result.
Helpful unwrap
The simplest case is almost like unwrap:
let x = Some;
let y: = Ok;
assert_eq!;
assert_eq!;
...but if you instead use it on a None or Err value:
let z = None;
let y = inner!;
...it will panic, with an error message that points you to a more helpful location than some line number inside libcore:
thread "test" panicked at "Unexpected value found inside "z"", src/lib.rs:23
Error handling
If panic isn't an option - and it usually isn't - just add an else clause:
let x: = Err;
let y = inner!;
// Since x is an Err, we'll never get here.
println!;
You can use the else clause to compute a default value, or use flow control
(e g break, continue, or return).
Want access to what's inside the Err value in your else clause?
No problem, just add a |variable| after else, like this:
let x: = Err;
let y = inner!;
assert_eq!;
Note: This does not turn your else clause into a closure, so you can still use
(e g) return the same way as before.
It works with your enums too
It does not work only with Option and Result. Just add an if clause:
let z = Apple;
let y = inner!;
assert_eq!;
You can skip the else clause to panic in case the enum is not
the expected variant.
Note that in this case, the entire item (instead of the contents inside
Err) is passed on to the else clause:
let z = Orange;
inner!;
You can also turn your enum into a Option with the Some macro:
assert_eq!;
assert_eq!;
assert_eq!;
Or into a Result with the ok!() macro:
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Notice that the ok!() macro has an optional or clause that encapsulates the
expression in an Err, whereas the else clause gives you maximum flexibility
to return either an Err or an Ok.
Another option is to implement this crate's IntoResult trait for
your enum. Then you don't have to write an if clause to tell what
enum variant you want to descend into, and you can choose more than
one enum variant to be Ok:
assert_eq!;
License
Apache2.0/MIT