first of all I want to mention that there many similar question on StackOverflow and around the web but I just can't figure out how to solve this error for my case.
So I have a struct, which represents my own error type:
#[derive(Debug)]
pub struct Error {
msg: String,
}
Then I continued implementing Display
and std::error::Error
for my error type:
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
}
}
Now I tried to implement std::convert::From
so I can use my error type seamlessly with the ?
operator:
impl From<dyn std::error::Error> for Error {
fn from(err: dyn std::error::Error) -> Self {
Error {
msg: err.to_string(),
}
}
}
But then the rust-compiler gives me this error:
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
|
I know that by default, generic functions will work only on types that have a known size at compile time. But I cant figure out how to solve this problem properly.
Thanks for your help!
Link to code on Rust-Playground:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=568900e8c7847c1f79781fa9bb6d499d
As @SirDarius says above, you can't do this for an Error
because Error is not a type, it's a trait. (If you're coming from OOP, think of a Trait like an interface. You can't convert an interface into another type of object because the interface doesn't have any underlying state -- there's no "there" there.)
The right way to handle this is to implement From for each concrete type you need to support. This video really helped me understand how this all fits together.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With