Rust failed to downcast_ref from trait object extended from Any

Viewed 297

Here is the Rust Playground of the example code.

use std::any::Any;

pub trait MemorizedOutput: Any {
    fn as_any(&self) -> &dyn Any;
}

impl<T: Any> MemorizedOutput for T {
    fn as_any(&self) -> &dyn Any {
        self
    }
}

fn main() {
    let a = Box::new(1i32) as Box<dyn MemorizedOutput>;
    println!("{}", a.as_any().downcast_ref::<i32>().unwrap());
}

Why is the above code panic at unwrap().

1 Answers

Box<dyn MemorizedOutput> implements Any, so it is covered by the blanket implementation of MemorizedOutput. As per https://doc.rust-lang.org/reference/expressions/method-call-expr.html, Rust will prefer methods implemented on Box<dyn MemorizedOutput> before it the dereferenced type dyn MemorizedOutput. So a.as_any() is actually <Box<dyn MemorizedOutput> as MemorizedOutput>::as_any(&a), which obviously cannot be downcasted into i32.

Related