1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#[macro_export]
/// Helper macro for unwrapping `Option` values while returning early with an
/// error if the value of the expression is `None`. Can only be used in
/// functions that return `Option` because of the early return of `None` that
/// it provides.
///
/// # Examples
///
/// ```
/// #[macro_use]
/// extern crate try_opt;
///
/// use std::collections::HashMap;
///
/// fn map_add_checked(map: &HashMap<&str, i32>, lhs: &str, rhs: &str) -> Option<i32> {
///     let lhs = try_opt!(map.get(lhs));
///     let rhs = try_opt!(map.get(rhs));
///     lhs.checked_add(*rhs)
/// }
///
/// fn main() {
///     let mut map = HashMap::new();
///     map.insert("foo", 2);
///     map.insert("bar", 4);
///     map.insert("baz", 12);
///     assert_eq!(map_add_checked(&map, "foo", "bar"), Some(6));
///     assert_eq!(map_add_checked(&map, "baz", "qux"), None);
/// }
/// ```
macro_rules! try_opt {
    ($e:expr) =>(
        match $e {
            Some(v) => v,
            None => return None,
        }
    )
}