Why does casting to &Trait require Sized?

I've created a trait that I need to implement among other types for str. I also need to collect instances of the trait in a heterogeneous way, so I wanted to use &Trait. But when I tried to pass &str as `&Trait, I got

error: the trait `core::marker::Sized` is not implemented for the type `str` [E0277]

So I've tested it and found that reference to unsized concrete type (&str, &[T]) simply can't be converted to reference to trait type. For test there is no need to create own trait, std::fmt::Display will do—let x:&Display = "x" gives the same error as does let x = "x" as &Display.

But why? Trait types are unsized by their nature, so whatever will use the result does not care and no allocation is being done for which the size would be needed.

1 Like

@nikomatsakis's PR that made the change talks about the reasoning: Require that objects can only be made from Sized types. Fixes #18333. by nikomatsakis · Pull Request #18750 · rust-lang/rust · GitHub