Why downcast_ref() is not available on Trait : Any?


#1
struct Inherited;
struct Direct;

use std::any::Any;

trait Tr : Any {}

impl Tr for Inherited {}


fn main() {
    let a: Box<Any> = Box::new(Direct);
    let b: Box<Tr> = Box::new(Inherited);
    
    let a: &Direct = a.downcast_ref().unwrap();
    
    // Does not compile:
    // let b: &Inherited = b.downcast_ref().expect("that should work too");
    
    let b: &Inherited = (&b as &Any).downcast_ref().expect("that should work too");
}

https://is.gd/qjKbZK

Since the trait implements Any, I’d expect it to support Any's methods. But somehow it doesn’t, and casting Box to reference seems to change how the type is interpreted, because the cast fails. What’s going on here?


#2

This StackOverflow answer to “How to get a struct reference from a boxed trait?” might help.


#3

Any is a peculiar construct, so it has something you might not have seen before: downcast_ref is not a method in the definition of the trait. It’s a method that the type Any itself has as an intrinsic method — the type Any is the object type of the trait with the same name! So you’ll only be able to call downcast_ref on &Any, Box<Any> etc.