Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust failed to downcast_ref from trait object extended from Any

Tags:

rust

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().

like image 666
Ziping Sun Avatar asked Nov 16 '25 19:11

Ziping Sun


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.

like image 55
Gary Guo Avatar answered Nov 18 '25 21:11

Gary Guo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!