Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 429
Samuel Dressel Avatar asked Feb 07 '20 13:02

Samuel Dressel


1 Answers

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.

like image 127
Tim Keating Avatar answered Oct 17 '22 13:10

Tim Keating