Associated type "inherits" sizedness of `Self`?

Given:

trait Foo {
    type Bar;
}

Is there any way to express that, for T: Foo, if T: Sized, then T::Bar: Sized? I suspect not, but maybe there's some clever hack I'm not thinking of.

I doubt it. This is the kind of thing you would specify when you use the trait F: Foo<Bar = B> + Sized, B: Sized (Sized is usually automatic but you get the idea). There's also no !Sized, so idk what you'd do with such a restriction.

type Bar; always requires that Bar is Sized.

... but this compiles.

Hmm… let’s take some type equality trait, and then we can start with

trait Foo {
    type Bar: ?Sized;
}

and add a second associated type equal to the first, and bounded by Sized … i.e. like this:

pub trait TypeIsEqual {
    type To: ?Sized;
}
impl<T: ?Sized> TypeIsEqual for T {
    type To = Self;
}

trait Foo {
    type Bar: ?Sized;
    type BarSized: Sized + TypeIsEqual<To = Self::Bar>
    where
        Self: Sized;
}

(I know the BarSized: Sized bound is redundant, but it’s more explicit this way)

Now the hackiness level of this is quite high. (In fact it’s already nontrivial to implement this at all for some non-Sized type.) This trait definition certainly not very comfortable to work with, in fact depending on what your exact use-case is like, it may probably not be usable at all.

On that matter, feel free to actually do share more about your use-case, then we could discuss the trickeries that could make this approach actually work.

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.