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().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With