[英]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,
}
然后我继续为我的错误类型实现Display
和std::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 上的代码:
正如上面@SirDarius 所说,您不能对Error
执行此操作,因为 Error 不是一种类型,而是一种特征。 (如果您来自 OOP,请将 Trait 视为接口。您不能将接口转换为另一种类型的对象,因为接口没有任何底层状态——那里没有“那里”。)
处理这个问题的正确方法是为您需要支持的每个具体类型实现 From 。 这个视频真的帮助我理解了这一切是如何组合在一起的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.