#try #return #early #options

deprecated try_opt

[deprecated] Like try!, but for Option

3 unstable releases

Uses old Rust 2015

0.2.0 Jan 22, 2019
0.1.1 Jul 5, 2015
0.1.0 Jul 5, 2015

#35 in #early

Download history 47/week @ 2024-03-15 57/week @ 2024-03-22 116/week @ 2024-03-29 44/week @ 2024-04-05 49/week @ 2024-04-12 52/week @ 2024-04-19 48/week @ 2024-04-26 43/week @ 2024-05-03 48/week @ 2024-05-10 47/week @ 2024-05-17 48/week @ 2024-05-24 47/week @ 2024-05-31 27/week @ 2024-06-07 42/week @ 2024-06-14 49/week @ 2024-06-21 19/week @ 2024-06-28

145 downloads per month
Used in 8 crates (5 directly)

MIT license

4KB

Deprecated

Rust now allows the ? operator to be used on Option. The try_opt! example further below can be rewritten as the following:

use std::collections::HashMap;

fn map_add_checked(map: &HashMap<&str, i32>, lhs: &str, rhs: &str) -> Option<i32> {
    let lhs = map.get(lhs)?;
    let rhs = 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);
}

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);
}

No runtime deps