如何在Rust中为具体的错误类型和Box <Error>实施From?

Nic*_*hop 3 rust

这是我的测试代码:

use std::error::Error;
use std::fmt;

struct Handler {
    error: String
}

#[derive(Debug)]
struct SpecificError;

impl fmt::Display for SpecificError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "SpecificError")
    }
}

impl Error for SpecificError {}

impl<E: Error> From<E> for Handler {
    fn from(e: E) -> Self {
        Handler { error: format!("{}", e) }
    }
}

fn fail1() -> Result<(), SpecificError> {
    Err(SpecificError)
}

fn fail2() -> Result<(), Box<Error>> {
    Err(Box::new(SpecificError))
}

fn handler() -> Result<(), Handler> {
    fail1()?;
    fail2()?;
    Ok(())
}
Run Code Online (Sandbox Code Playgroud)

对的调用fail1()很好,但是对的调用fail2()无法编译:

error[E0277]: the size for values of type `dyn std::error::Error` cannot be known at compilation time
  --> src/main.rs:35:5
   |
35 |     fail2()?;
   |     ^^^^^^^^ doesn't have a size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `dyn std::error::Error`
   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
   = note: required because of the requirements on the impl of `std::error::Error` for `std::boxed::Box<dyn std::error::Error>`
   = note: required because of the requirements on the impl of `std::convert::From<std::boxed::Box<dyn std::error::Error>>` for `Handler`
   = note: required by `std::convert::From::from`
Run Code Online (Sandbox Code Playgroud)

我同意dyn Error没有在编译时知道大小的编译器,但是我不明白为什么这样做很重要,因为我要转换的类型是a Box<dyn Error>,在编译时确实知道大小。

She*_*ter 5

TL; DR:我敢肯定,您不能以一种通用的方式。

我不明白为什么这样做很重要,因为我尝试从中转换的类型是Box<dyn Error>,在编译时确实知道它的大小。

那不是它抱怨的地方。再次查看错误消息(稍作清理):

the trait `Sized` is not implemented for `dyn Error`
required because of the requirements on the impl of `Error` for `Box<dyn Error>`
required because of the requirements on the impl of `From<Box<dyn Error>>` for `Handler`
required by `From::from`
Run Code Online (Sandbox Code Playgroud)

第二行很重要。这是您的问题的更简单再现:

use std::error::Error;

fn example<E: Error>() {}

fn main() {
    example::<Box<dyn Error>>();
}
Run Code Online (Sandbox Code Playgroud)
use std::error::Error;

fn example<E: Error>() {}

fn main() {
    example::<Box<dyn Error>>();
}
Run Code Online (Sandbox Code Playgroud)

Erroris 实现,Box<T>TSized并实现Error自身:

impl<T: Error> Error for Box<T> {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

换句话说,Box<dyn Error> 不执行Error

可能有人认为您可以添加Fromfor 的第二种实现Box<Error>,但这是不允许的:

error[E0277]: the size for values of type `dyn std::error::Error` cannot be known at compilation time
 --> src/main.rs:6:5
  |
6 |     example::<Box<dyn Error>>();
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `dyn std::error::Error`
  = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
  = note: required because of the requirements on the impl of `std::error::Error` for `std::boxed::Box<dyn std::error::Error>`
note: required by `example`
 --> src/main.rs:3:1
  |
3 | fn example<E: Error>() {}
  | ^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

我必须提供的最佳替代方案是为From您需要支持的每种具体类型实施:

impl From<SpecificError> for Handler {
    fn from(e: SpecificError) -> Self {
        Handler { error: format!("{}", e) }
    }
}

impl From<Box<dyn Error>> for Handler {
    fn from(e: Box<dyn Error>) -> Self {
        Handler { error: format!("{}", e) }
    }
}
Run Code Online (Sandbox Code Playgroud)

宏可以减少此处的样板。