Use of raw trait object in return type of method in trait

Hi! I’m curious as to why I can declare a method with return type “dyn Trait” (not a reference or box, just the raw “dyn Trait”) inside a trait. For example:

trait Foo {

trait Bar {
    fn make_foo(self) -> dyn Foo;

AFAICT it’s impossible to ever implement Bar, because dyn Foo can’t be a return type because it doesn’t have fixed size. So why does this code compile? Is there some fancy feature I’m missing, maybe something about return type covariance, that makes it possible to implement Bar in the above example? I tried an implementation that returns Box<dyn Foo> but, quite understandably, that’s rejected for having the wrong return type.

Interesting. Methods like fn f() -> [u8] are also allowed. I am pretty sure there is no way to implement such methods.

As a guess, I imagine this might be related to the handling of methods like fn f(self) -> Self. Methods are allowed to have argument or return types that are not known to be Sized, and checking of Sized constraints is done on the implementations instead.

OK, from your reply it sounds like the answer is more along the lines of “the compiler isn’t checking something that it could be”, not “there is some obscure feature I don’t know about which makes this actually useful”. That pretty much satisfies me; if such a declaration had been usable somehow I would want to know about it, but if it’s not, the lack of checking doesn’t really bother me. Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.