【问题标题】:error handling, map_err and error type conversion错误处理、map_err 和错误类型转换
【发布时间】:2022-01-02 05:03:57
【问题描述】:

我正在学习 rust,目前正在练习 here

到目前为止,我想出了以下几点:

impl ParsePosNonzeroError {
   ...
   ...
   fn from_parseint(err: ParseIntError) -> ParsePosNonzeroError {
       ParsePosNonzeroError::ParseInt(err)
   }
fn parse_pos_nonzero(s: &str)
-> Result<PositiveNonzeroInteger, ParsePosNonzeroError>
{
     let x: i64 = s.parse::<i64>().map_err(ParsePosNonzeroError::from_parseint);
     PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation)
}

当我这样做时,我收到错误消息:

! Compiling of exercises/error_handling/errors6.rs failed! Please try again. Here's the output:
error[E0308]: mismatched types
  --> exercises/error_handling/errors6.rs:34:18
   |
34 |       let x: i64 = s.parse::<i64>()
   |  ____________---___^
   | |            |
   | |            expected due to this
35 | |         .map_err(ParsePosNonzeroError::from_parseint);
   | |_____________________________________________________^ expected `i64`, found enum `Result`
   |
   = note: expected type `i64`
              found enum `Result<i64, ParsePosNonzeroError>`

浏览map_err 的文档,我看到以下内容: Maps a Result&lt;T, E&gt; to Result&lt;T, F&gt; by applying a function to a contained Err value, leaving an Ok value untouched.

我错过了什么?为什么这不起作用?

【问题讨论】:

    标签: rust error-handling


    【解决方案1】:

    map_err 正在返回 Result&lt;i64, ParsePosNonzeroError&gt;,但您试图将其影响到 x,您将其声明为 i64 变量。您需要添加 ? 以便返回 Err 结果并解包 Ok 结果:let x = s.parse::&lt;i64&gt;().map_err(ParsePosNonzeroError::from_parseint)?;

    【讨论】:

      【解决方案2】:

      作为对 Jmb 回答的补充,请注意 ? 已经在此处手动完成了您正在做的事情:

      foo?
      

      脱糖,或多或少1

      match foo {
          Ok(foo) => foo,
          Err(e) => return Err(From::from(e));
      }
      

      因此您可以只使用impl From&lt;ParseIntError&gt; for ParsePosNonzeroError ,而? 将根据parse 的错误类型与parse_pos_nonzero 的错误类型之间的差异隐式执行转换。


      1:Try trait 稍微复杂一些,但对于基本使用来说已经足够了

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        • 2013-09-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多