Does dyn Any support unsized types?

#1

dyn Trait is implemented for T: 'static + ?Sized. Therefore something like the following is completely normal usage, and it compiles:

fn foo(x: &dyn Any) {
    if let Some(x) = x.downcast_ref::<usize>() {
        println!("{:?}", x);
    }
}

Now, say I wanted to test if x was an &[u8]:

fn foo(x: &dyn Any) {
    if x.is::<[u8]>() {
        println!("x is [u8]");
    }
}

This does not work. I can understand if downcast_ref wouldn’t work directly because of the unsizedness of the interior value and the need to produce a vtable/length etc. But is<T> should work, given that it is implemented for ?Sized types. The thing is, is<T> is declared like so:

pub fn is<T: Any>(&self) -> bool;

Meaning that I can no longer put in a ?Sized type for T. Is this done on purpose or is this an erroneous oversight?

0 Likes

#2

No Any doesn’t support ?Sized types. This is because you can’t unsize !Sized types, so there is no way to make dyn Any from a [T].

1 Like

#3

Ah, I see, a bit of playground-ing has revealed that there is, in fact, no way to make a dyn Any where the underlying type is : ?Sized. But it still leaves to question why Any is implemented for ?Sized types.

0 Likes

#4

For completenes if we get a way to convert between unsized types.

0 Likes