繁体   English   中英

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 和网络上有很多类似的问题,但我就是不知道如何解决我的案例中的这个错误。

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

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

然后我继续为我的错误类型实现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
    }
}

现在我尝试实现std::convert::From以便我可以将我的错误类型与? 操作员:

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

但是然后 rust-compiler 给了我这个错误:

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&mode=debug&edition=2018&gist=568900e8c7847c1f79781fa9bb6d499d

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM