不能对返回 Result<(), error> 的函数使用 `?` 运算符 [英] Cannot use `?` operator for functions that return Result<(), error>
本文介绍了不能对返回 Result<(), error> 的函数使用 `?` 运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以这个例子为例:
fn function() -> Result<(), &'static str> {
Ok(())
}
fn main() {
function()?; // Compile error
}
我收到错误:cannot use the ?返回 () 的函数中的运算符
.
为什么我不能将 ?
运算符用于此类功能?是否有语法糖来避免使用 match
语句?
Why can't I use the ?
operator for such functions? Is there syntactic sugar to avoid using a match
statement?
推荐答案
如果 function()
返回 Err
结果,您希望发生什么?您不能使用 try!
/?
因为它会导致包含函数返回相同的 Err
,但是 main()
不能返回 Err
(它返回 ()
,而不是 Result<…>
).如果你想恐慌,你可以使用 unwrap
:
What do you want to happen if function()
returns an Err
result? You can’t use try!
/?
because it causes the containing function to return the same Err
, but main()
can’t return an Err
(it returns ()
, not Result<…>
). If you want to panic, you can use unwrap
:
function().unwrap();
如果你想忽略错误,丢弃结果:
If you want to ignore errors, discard the result:
let _ = function();
这篇关于不能对返回 Result<(), error> 的函数使用 `?` 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文