如何处理 ?Rust 中的运算符,用于函数返回类型不能为 Result<T, E> 的情况

0 rust

我正在读关于?运算符并想在没有类型的函数中使用它Result<T, E>。下面提到的部分写在其中:

\n
\n

此错误指出我们\xe2\x80\x99re 只允许在返回、或实现 的其他类型的?函数中使用运算符。ResultOptionFromResidual

\n

要修复该错误,您有两种选择。一种选择是更改函数的返回类型,使其与您使用运算符的值兼容,?只要您没有任何限制即可。另一种技术是使用匹配或其中一种方法以任何适当的方式Result<T, E>来处理。Result<T, E>

\n
\n

我没有看到这个的实现,只是在语句之​​前写 match 与 ? 不起作用。\n我如何捕获该错误并使用它为我的函数返回一些其他依赖值。

\n

我的代码看起来像这样(显然,它没有运行)...我对实现相同功能的其他方式并不真正感兴趣,相反,我问是否可以使用这个具有此特定配置的特定操作员。

\n
fn error_handling() -> String{\n\n    //the ? operator (replaces the try macro)\n    //Shorthand, passes the Ok() value out while returns the Err() value.\n    //Also can pass the Some() value from Option<T> and return None value.\n    //\n    //If function doesn\'t have the return type as Result<T, E> then either extract\n    //the value out of Ok with a match statement or change the Return type in code.\n\n\n    let mut result = String::new();\n\n    let file_return = match fs::File::open("something.txt")? {\n        Ok(data) => data.read_to_string(&mut result),\n        Err(_) => &result.clear()\n    }\n    result\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Mas*_*inn 5

如何捕获该错误并使用它为我的函数返回一些其他依赖值。

只需删除?. expr?本质上就是这样:

match expr {
    Ok(v) => v,
    Err(e) => return Err(e)
}
Run Code Online (Sandbox Code Playgroud)

如果有错误,它会执行“立即返回”错误,否则允许您使用未包装的值。所以类型

fs::File::open("something.txt")?
Run Code Online (Sandbox Code Playgroud)

不是。FileResult<File, ...>因此,该比赛不再有效。

顺便说一句,match 你在这里写的你最初写的存在于标准库中,它被称为expect,所以你几乎可以写

fs::File::new("something.txt").expect("something bad happened")
Run Code Online (Sandbox Code Playgroud)

新版本还有一个内置的快捷方式(有点):std::fs::read_to_string

fs::File::open("something.txt")?
Run Code Online (Sandbox Code Playgroud)

应该与您编写的代码等效。