如何为具体的错误类型和Box实现From 在鲁斯特?

问题描述 投票:3回答:1

这是我的测试代码:

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(())
}

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`

我同意编译器dyn Error在编译时没有已知的大小,但我不明白为什么这是相关的,因为我试图转换的类型是Box<dyn Error>,它的编码大小已知时间。

rust
1个回答
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`

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

use std::error::Error;

fn example<E: Error>() {}

fn main() {
    example::<Box<dyn 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>() {}
  | ^^^^^^^^^^^^^^^^^^^^^^

Error只是implemented for Box<T> when T is Sized并实施Error本身:

impl<T: Error> Error for Box<T> {
    // ...
}

换句话说,Box<dyn Error>没有实施Error

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

upstream crates may add new impl of trait `std::error::Error` for type
`std::boxed::Box<(dyn std::error::Error + 'static)>` in future versions

我必须提供的最佳替代方案是为您需要支持的每种具体类型实施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) }
    }
}

宏可以减少这里的样板。

© www.soinside.com 2019 - 2024. All rights reserved.