Rust 错误:在编译时无法知道类型为 `(dyn std::error::Error \\’static)` 的值的大小

Rust Error: The size for values of type `(dyn std::error::Error + 'static)` cannot be known at compilation time

首先我想提一下,在 StackOverflow 和网络上有很多类似的问题,但我就是不知道如何解决我的案例中的这个错误。

所以我有一个结构体,它代表我自己的错误类型:

1
2
3
4
#[derive(Debug)]
pub struct Error {
    msg: String,
}

然后我继续为我的错误类型实现 Displaystd::error::Error

1
2
3
4
5
6
7
8
9
10
11
impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,"{}", self.msg)
    }
}

impl std::error::Error for Error {
    fn description(&self) -> &str {
        &self.msg
    }
}

现在我尝试实现 std::convert::From 以便我可以通过 ? 操作符无缝使用我的错误类型:

1
2
3
4
5
6
7
impl From<dyn std::error::Error> for Error {
    fn from(err: dyn std::error::Error) -> Self {
        Error {
            msg: err.to_string(),
        }
    }
}

但随后 rust 编译器给了我这个错误:

1
2
3
4
5
6
7
error[E0277]: the size for values of type `(dyn std::error::Error + 'static)` cannot be known
at compilation time
  --> wasm_api/geohub_wasm_filehandler_api/src/lib.rs:33:6
   |
33 | impl From<dyn std::error::Error> for Error {
   |      ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
   |

我知道默认情况下,泛型函数仅适用于编译时已知大小的类型。但我不知道如何正确解决这个问题。

感谢您的帮助!

Rust-Playground 代码链接:

https://play.rust-lang.org/?version=stable


正如@SirDarius 上面所说的,你不能对 Error 这样做,因为 Error 不是一种类型,它是一种特征。 (如果你来自 OOP,把 Trait 想象成一个接口。你不能把接口转换成另一种类型的对象,因为接口没有任何底层状态——没有"那里"那里。)

处理此问题的正确方法是为您需要支持的每个具体类型实现 From。这个视频真的帮助我理解了这一切是如何组合在一起的。