3个不稳定版本
使用旧的Rust 2015
| 0.2.0 | 2019年1月22日 |
|---|---|
| 0.1.1 | 2015年7月5日 |
| 0.1.0 | 2015年7月5日 |
#35 在 #early
145 每月下载量
在 8 个crate(5个直接) 中使用
4KB
已弃用
Rust现在允许在 ? 操作符上使用 Option。下面的 try_opt! 示例可以重写为以下内容
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);
}
用于解包 Option 值的辅助宏,如果表达式的值为 None 则提前返回错误。由于它提供了 None 的提前返回,因此只能用于返回 Option 的函数。
示例
#[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);
}