[英]Is it idiomatic Rust to accept a Result<T, E> as a function argument?
Consider the following code:考虑以下代码:
fn foo(x: i32) -> Result<i32, Error> {
//...
}
fn bar(x: Result<i32,Error>) -> Result<i32, Error> {
//...
}
fn main() {
let y = bar(foo(2)).unwrap();
}
Is this idiomatic, to pass the Result
type around?这是惯用的,传递
Result
类型吗? Or should you handle the error or unwrap the result of bar()
before passing the i32
directly.或者您应该在直接传递
i32
之前处理错误还是解开bar()
的结果。
It's quite unusual to accept a Result
as an argument, except in general purpose libraries for dealing with Result
s.接受
Result
作为参数是很不寻常的,除非在用于处理Result
的通用库中。
Result
has a lot of methods which help make working with it more ergonomic. Result
有 很多方法可以帮助使用它更符合人体工程学。 For example, and_then
, which chains a function call onto a previous result.例如,
and_then
将 function 调用链接到先前的结果。 Your example can be changed to:您的示例可以更改为:
fn foo(x: i32) -> Result<i32, Error> {
//...
}
fn bar(x: i32) -> Result<i32, Error> {
//...
}
fn main() {
let y = foo(2).and_then(|value| bar(value)).unwrap();
// or more concisely in this simple case:
let y = foo(2).and_then(bar).unwrap();
}
I can't say I've seen a situation where it made much sense but without a clearer explanation as to why you'd do that it's difficult to help more.我不能说我见过的情况很有意义,但如果没有更清楚地解释你为什么要这样做,就很难提供更多帮助。
Essentially, does bar
have any use for an Err()
input, or is it just going to pass that through directly?本质上,
bar
对Err()
输入有任何用处,还是直接通过它? In the former case, then yes it might make sense for bar
to take a Result
-- though given you're asking the question that looks unlikely在前一种情况下,是的,
bar
获取Result
可能是有意义的——尽管考虑到您提出的问题看起来不太可能
However if bar
starts with something along the lines of但是,如果
bar
以类似于以下内容的内容开头
fn bar(x: Result<i32, Error>) -> Result<i32, Error> {
let y = x?;
// work with an actual `i32` and potentially output an error as well
that is it has no actual use for an Err
, then no, it's not idiomatic, the input is unnecessarily and uselessly complicated.也就是说,它对
Err
没有实际用途,那么不,它不是惯用的,输入是不必要且无用的复杂。
In this case what you'd want is:在这种情况下,您想要的是:
fn bar(x: i32) -> Result<i32, Error> {
//...
}
fn main() {
let y = foo(2).and_then(bar).unwrap();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.