Please could someone explain why if an error is put behind a Box
, downcast_ref::<MyError>()
returns None
? I don't really gain understanding from the Box or Error documentation.
Here's a snippet (playground):
use std::{error::Error, fmt::{self, Display, Formatter}};
// === //
#[derive(Debug)]
struct MyError;
impl Display for MyError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "MyError") }
}
impl Error for MyError {}
// === //
#[derive(Debug)]
struct Inner<T: ?Sized> {
error: T,
}
#[derive(Debug)]
pub struct ErrorWrapper {
inner: Box<Inner<dyn Error + Send + Sync>>,
}
impl ErrorWrapper {
pub fn new<E>(error: E) -> Self
where
E: 'static + Error + Send + Sync,
{
Self {
inner: Box::new(Inner {
error: Box::new(error),
}),
}
}
pub fn as_error(&self) -> &(dyn Error + 'static) {
&self.inner.error
}
}
fn main() {
let my_error = MyError;
let error: &dyn Error = &my_error;
println!("{:?}", error.downcast_ref::<MyError>());
let wrapper = ErrorWrapper::new(MyError);
println!("{:?}", wrapper.as_error().downcast_ref::<MyError>());
}
Output:
Some(MyError)
None