try_opt

Crates.iotry_opt
lib.rstry_opt
version0.2.0
sourcesrc
created_at2015-07-05 13:43:13.223704
updated_at2019-01-22 17:45:25.736615
description[deprecated] Like try!, but for Option
homepage
repositoryhttps://github.com/crumblingstatue/try_opt
max_upload_size
id2536
size3,691
(crumblingstatue)

documentation

README

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);
}
Commit count: 4

cargo fmt