Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I declare this struct which has an Optional error field?

How can I declare this struct correctly?

PLAYGROUND CODE

use std::{error};

pub struct AppError {
  msg: Option<String>,
  // error: Option<anyhow::Error>, // This works
  error: Option<dyn error::Error + Send + Sync + 'static>, // but I need this, not anyhow
}

the error is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

error[E0277]: the size for values of type `(dyn std::error::Error + Send + Sync + 'static)` cannot be known at compilation time
 --> src/lib.rs:6:10
  |
6 |   error: Option<dyn error::Error + Send + Sync + 'static>, // but I need this, not anyhow
  |          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `Sized` is not implemented for `(dyn std::error::Error + Send + Sync + 'static)`
note: required by a bound in `Option`

For more information about this error, try `rustc --explain E0277`.

How to fix this?

>Solution :

You can wrap your error in a Box

use std::{error};

pub struct AppError {
  msg: Option<String>,
  // error: Option<anyhow::Error>, // This works
  error: Option<Box<dyn error::Error + Send + Sync + 'static>>, // but I need this, not anyhow
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading