如何忽略从 Rust 函数返回的错误并继续进行? [英] How do I ignore an error returned from a Rust function and proceed regardless?

查看:55
本文介绍了如何忽略从 Rust 函数返回的错误并继续进行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当知道某段代码可能会抛出错误时,我们会使用 try/catch 块来忽略此类错误并继续.这是在错误不那么重要但也许我们只想记录它时完成的:

When it is known that some piece of code might throw an error, we make use of try/catch blocks to ignore such errors and proceed. This is done when the error is not that important but maybe we only want to log it:

try{
    int i = 1/0;
} catch( ArithmeticException e){
    System.out.println("Encountered an error but would proceed.");
} 
x = y;

Java 中的这种构造将继续执行 x = y;.

Such a construct in Java would continue on to execute x = y;.

我可以使用 match 来执行此操作或任何其他构造吗?

Can I make use of match to do this or any other construct?

我确实看到了一个 try! 宏,但它可能会在出现错误时返回方法的返回类型为 Result.

I do see a try! macro, but perhaps it would return in case of an error with the return type of the method as Result.

我想在 UT 中使用这样的构造,以确保它即使在发生错误后也能继续运行.

I want to use such a construct in a UT to ensure it continues to run even after an error has occurred.

推荐答案

Rust 中可能失败的函数返回一个 结果:

Functions in Rust which can fail return a Result:

Result 是用于返回和传播错误的类型.它是一个带有变量的枚举,Ok(T),表示成功并包含一个值,而 Err(E),表示错误并包含一个错误值.>

Result<T, E> is the type used for returning and propagating errors. It is an enum with the variants, Ok(T), representing success and containing a value, and Err(E), representing error and containing an error value.

我强烈建议阅读错误处理部分Rust Book 中:

I highly recommend reading the Error Handling section in the Rust Book:

Rust 有许多功能可以处理出现问题的情况

Rust has a number of features for handling situations in which something goes wrong

如果你想忽略一个错误,你有不同的可能性:

If you want to ignore an error, you have different possibilities:

  • 不要使用Result:

  let _ = failing_function();

该函数将被调用,但结果将被忽略.如果省略 let _ = ,则会收到警告.

The function will be called, but the result will be ignored. If you omit let _ = , you will get a warning.

使用if letmatch:

Ignore the Err variant of Result using if let or match:

  if let Ok(ret) = failing_function() {
      // use the returned value
  }

您也可以将 Result 转换为 Option 带有 Result::ok:

You may also convert the Result into Option with Result::ok:

  let opt = failing_function().ok();

  • 解开错误.如果发生错误,此代码会发生恐慌:

  • Unwrap the error. This code panics if an error occurred though:

      let ret = failing_function().unwrap();
      // or
      let ret = failing_function().expect("A panic message to be displayed");
    

  • try!() 解包结果并在发生错误时提前返回函数.但是,您应该使用 ? 而不是 try! 作为 已弃用.

    try!() unwraps a result and early returns the function, if an error occurred. However, you should use ? instead of try! as this is deprecated.

    另见:

    这篇关于如何忽略从 Rust 函数返回的错误并继续进行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆