我有这样的事情(真正的功能是从Ini::Section::get
rust-ini):
impl Foo {
pub fn get<K>(&'a mut self, key: &K) -> Option<&'a str>
where
K: Hash + Eq,
{
// ...
}
}
我有好几次把它叫做:
fn new() -> Result<Boo, String> {
let item1 = match section.get("item1") {
None => return Result::Err("no item1".to_string()),
Some(v) => v,
};
let item2 = match section.get("item2") {
None => return Result::Err("no item2".to_string()),
Some(v) => v,
};
}
要删除代码膨胀,我可以写这样的宏:
macro_rules! try_ini_get {
($e:expr) => {
match $e {
Some(s) => s,
None => return Result::Err("no ini item".to_string()),
}
}
}
有什么办法去除重复代码没有这个宏实现?
该ok_or
和ok_or_else
方法转换到Option
s Result
s和?
操作自动化早期Err
收益相关的样板。
你可以这样做:
fn new() -> Result<Boo, String> {
let item1 = section.get("item1").ok_or("no item1")?;
let item2 = section.get("item2").ok_or("no item2")?;
// whatever processing...
Ok(final_result)
}