如何定义将任何错误转换为标准错误类型的通用类型转换?

时间:2019-06-09 13:38:21

标签: rust

我想将其他包装箱返回的任何错误转换为我自己的错误类型,以便我可以在Result<X, CalendarError>中返回任何错误。

我正在尝试以下操作

use std::error::Error;

struct CalendarError {
    msg: String,
}

impl<Err> From<std::convert::From<Err>> for CalendarError
where
    Err: Error,
{
    fn from(err: Err) -> Self {
        CalendarError {
            msg: format!("error: {}", err),
        }
    }
}

我收到编译错误:

error[E0277]: the size for values of type `(dyn std::convert::From<Err> + 'static)` cannot be known at compilation time
 --> src/lib.rs:7:11
  |
7 | impl<Err> From<std::convert::From<Err>> for CalendarError
  |           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `(dyn std::convert::From<Err> + 'static)`
  = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>

error[E0038]: the trait `std::convert::From` cannot be made into an object
 --> src/lib.rs:7:11
  |
7 | impl<Err> From<std::convert::From<Err>> for CalendarError
  |           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::convert::From` cannot be made into an object
  |
  = note: the trait cannot require that `Self : Sized`

我该如何解决?

编辑:通过删除From定义,并添加以下内容,可以编译它(如在所引用的文章中所建议):

impl CalendarError {
    fn from_error<Err>(err: Err) -> Self
    where
        Err: Error,
    {
        CalendarError {
            msg: format!("error: {}", err),
        }
    }
} 

,然后将调用添加到map_err以显式进行转换:

let u = from_reader(reader).map_err(CalendarError::from_error)?;

0 个答案:

没有答案