How to implement `Error` for sources that are `Send + Sync`

I have this error type:

#[derive(Debug)]
pub struct UserFacing {
  pub msg: String,
  pub source: Option<Box<dyn Error + Send + Sync>>,
}

I've just recently added the Send + Sync bound because I want it to work inside a par_iter of rayon. Everything works out, basically, except: How do I implement Error for this?

The problem is fn source(&self) -> Option<&(dyn Error + 'static)> which does not have the Send + Sync bounds on the output. I've tried downcasting to no avail (because the target is a dyn rather than a concrete type), and google would not help out.

Any pointers welcome :slight_smile:

You have to explicitly tell the compiler to do the cast via a as _ for whatever reason: Rust Playground.

2 Likes

Alternatively, but slightly shorter, you could use self.source.as_deref().map(|s| s as _).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.