-
Notifications
You must be signed in to change notification settings - Fork 12.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Using associated type as struct field causes invariance w.r.t trait #57440
Comments
You cannot expect to have variance for associated types in general. If Knowing that You can still write a hand-written « cast » between |
I understand that, and wasn't expecting that. Instead, I was hoping that internally rust could treat
Do you mean like this?
For that to be useful, I'd have to be able to write the cast to be generic in |
Uh, I am not sure. Notice that you can have trait impls like In general, I don't see any reason why associated types should have any variance, ever. But I am also not an expert on this. |
I don't want
I don't want variance of the associated types. For my use case, they will never have a lifetime. But using the associated type as a field prevents variance w.r.t the trait type, which I do want. |
Yep, but if there is a generic impl But actually what I was asking is, if you know that
Yes that's what I was meaning. Annoying, but the only solution I guess. Basically you have to manually write casts for all your types that need sub-typing. If there are only a few, that might work. |
Well, that's pretty much the definition of subtype -- "it is safe to do the transmute". So, yes -- but now the hard part is making sure that it's really a subtype. |
Changing the workaround to the following avoids most of the downsides, since it lets me omit the extra type parameter in uses of the struct. It's still something I would expect the compiler to allow automatically, but I think this is good enough for me for now. pub struct S1<T, A = <T as Trait>::Assoc>
where
T: Trait<Assoc = A>,
{
pub t: T,
pub a: A,
} |
The following code:
fails with:
I would expect the variance of
S1
andS2
to be the same w.r.tT
. And even if this case can't be handled in general for all associated types, shouldn't theAssoc: 'static
bound allow it?I've been using
S1
as a workaround for this issue, but the problem with that is the extra type parameter propagates upwards into all containing types, and it gets quite ugly and verbose.The text was updated successfully, but these errors were encountered: