[Question] Typecasting to dyn trait

I was coding a statement where the compiler should cast into a dynamic trait, but apparantly it doesn't. In stead it issues an error that the resulting type is of the wrong (concrete) type. If I add a type annotation, everything is fine.

Is it true that casting to a dynamic type always need type annotation? I mean: does the compiler not do casting in that case?

Basically, yes.

When you use & on something, it's usually ambiguous and could mean several things, e.g. & on String could give &str, &String, &dyn Display, etc. So the compiler has to know somehow which one you want. Usually type inference finds the required type from context, but if you don't have enough context, it will require an explicit type annotation.

2 Likes

I think you're talking about coercion, which is something the compiler does implicitly, not casting, which is something the programmer does using the as operator.

The language reference has a page on coercions that explains in more detail what @kornel just mentioned. In particular,

A coercion can only occur at certain coercion sites in a program; these are typically places where the desired type is explicit or can be derived by propagation from explicit types (without type inference).

The Rustonomicon also has chapters on coercions and casts.

Thank you both, @kornel and @trentj! These comments will certainly help. I am marking the one with the links as the solution.