【发布时间】:2016-07-21 23:58:27
【问题描述】:
我有这样的代码:
let things = vec![/* ...*/]; // e.g. Vec<String>
things
.map(|thing| {
let a = try!(do_stuff(thing));
Ok(other_stuff(a))
})
.filter(|thing_result| match *thing_result {
Err(e) => true,
Ok(a) => check(a),
})
.map(|thing_result| {
let a = try!(thing_result);
// do stuff
b
})
.collect::<Result<Vec<_>, _>>()
在语义方面,我想在第一个错误后停止处理。
上面的代码可以用,但是感觉挺麻烦的。有没有更好的办法?我查看了文档中的 filter_if_ok 之类的内容,但没有找到任何内容。
我知道collect::<Result<Vec<_>, _>>,它工作得很好。我特别想消除以下样板:
- 在过滤器的关闭中,我必须在
thing_result上使用match。我觉得这应该只是一个单行,例如.filter_if_ok(|thing| check(a))。 - 每次我使用
map时,我都必须包含一个额外的语句let a = try!(thing_result);以处理Err的可能性。同样,我觉得这可以抽象为.map_if_ok(|thing| ...)。
我可以使用另一种方法来获得这种简洁程度,还是我只需要坚持下去?
【问题讨论】:
标签: rust iterator map-function filterfunction rust-result