Associated types where Self: Sized

Say you have this trait:

trait Trait {
    type Assoc;
}

Can you create a value of type &dyn Trait without specifying Assoc?

===========

More thoughts:

I see a parallel here with where Self: Sized on methods. Traits have two aspects to them: compile-time generics, and type-erased unsized trait objects. This split is the reason for object safety rules. A trait function fn foo(self) is not object safe because at runtime you can't know the size of self. HOWEVER by using fn foo(self) where Self: Sized, you can tell the compiler a method isn't relevant for trait objects.

I want the equivalent for associated types, something like this:

trait Trait {
    type Assoc where Self: Sized;
}

telling the compiler that Assoc isn't relevant for trait objects, only for monomorphized usage. Does such a thing exist?

No, but you can create another trait and have a blanket impl always implement that other trait when your trait is implemented. Then you can use &dyn YourNewTrait.

2 Likes

That's so obvious! I can't believe I didn't think of it haha