Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/crumblingstatue/try_opt
[Deprecated] Like try!, but for Option
https://github.com/crumblingstatue/try_opt
Last synced: 3 months ago
JSON representation
[Deprecated] Like try!, but for Option
- Host: GitHub
- URL: https://github.com/crumblingstatue/try_opt
- Owner: crumblingstatue
- Created: 2015-07-05T13:42:28.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2019-01-22T17:44:18.000Z (almost 6 years ago)
- Last Synced: 2024-10-07T05:09:13.590Z (3 months ago)
- Language: Rust
- Homepage:
- Size: 1.95 KB
- Stars: 5
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Deprecated
Rust now allows the `?` operator to be used on `Option`. The `try_opt!` example further below
can be rewritten as the following:```Rust
use std::collections::HashMap;fn map_add_checked(map: &HashMap<&str, i32>, lhs: &str, rhs: &str) -> Option {
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
```Rust
#[macro_use]
extern crate try_opt;use std::collections::HashMap;
fn map_add_checked(map: &HashMap<&str, i32>, lhs: &str, rhs: &str) -> Option {
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);
}
```