Rust 错误:编译时无法知道“(dyn std::error::Error + 'static)”类型值的大小

Sam*_*sel 17 error-handling compiler-errors traits rust

首先,我想提一下,StackOverflow 和网络上有很多类似的问题,但我只是不知道如何针对我的情况解决此错误。

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

#[derive(Debug)]
pub struct Error {
    msg: String,
}
Run Code Online (Sandbox Code Playgroud)

然后我继续实施Displaystd::error::Error针对我的错误类型:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我尝试实现,std::convert::From以便我可以与运算符无缝地使用我的错误类型?

impl From<dyn std::error::Error> for Error {
    fn from(err: dyn std::error::Error) -> Self {
        Error {
            msg: err.to_string(),
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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
   |
Run Code Online (Sandbox Code Playgroud)

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

感谢您的帮助!

Rust-Playground 上的代码链接:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=568900e8c7847c1f79781fa9bb6d499d

Tim*_*ing 8

正如上面@SirDarius 所说,您不能为 an 执行此操作,Error因为 Error 不是一种类型,而是一种特征。(如果您来自 OOP,请将 Trait 视为接口。您不能将接口转换为另一种类型的对象,因为接口没有任何底层状态——那里没有“那里”。)

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