【发布时间】:2019-04-07 15:53:51
【问题描述】:
Result::and_then() 非常适合编写控制流。
fn some_fn() -> Result<String, Error> {
Ok("Yay".to_string())
}
some_fn()
.and_then(|value| some_other_fn())
.and_then(|some_other_value| /* ... */)
有时我们想要创建一个副作用并仍然传播发出的值。假设我们想在收到值的那一刻打印它:
some_fn()
.and_then(|value| {
println!("{}", &value);
some_other_fn()
})
.and_then(|some_other_value| /* ... */)
有没有更好的方法来做到这一点?像Reactive Extensions' tap() operator 这样的东西会很棒。
【问题讨论】:
-
我们想在收到值的那一刻打印出来——但你还是想打电话给
some_other_function?如果是这样,你有什么问题? -
这正是我所指的。我所拥有的一切都没有问题。我只是睁大眼睛和耳朵以获得更优雅的解决方案(如果可能的话)。一如既往,您的回答非常有道理 - 谢谢!
-
副作用永远不会优雅
标签: rust control-flow