Unintended invariance caused by associated type projections

In SmallVec v1, SmallVec<A> is invariant with respect to the generic parameter A. The reason is that its fields use the associated type projection A::Item, and the compiler treats that projection as invariant with respect to A.

We can see this directly in the v1 source code. The Array trait defines the associated type, and the implementation for arrays confirms that A::Item is T:

pub unsafe trait Array {
    type Item;
    fn size() -> usize;
}

// When A = [T; N]
unsafe impl<T, const N: usize> Array for [T; N] {
    type Item = T;
    // ...
}

Then, inside the SmallVec struct itself, we have a PhantomData<A::Item>:

pub struct SmallVec<A: Array> {
    capacity: usize,
    data: SmallVecData<A>,
    _marker: PhantomData<A::Item>,
}

And the internal data storage also directly relies on the projection:

union SmallVecData<A: Array> {
    inline: core::mem::ManuallyDrop<MaybeUninit<A>>,
    heap: (NonNull<A::Item>, usize),
}

Because these projections are invariant, SmallVec<A> becomes invariant over A. And since A::Item = T when A = [T; N], this also makes SmallVec<[T; N]> invariant with respect to T, including lifetimes.

This often surprises users who expect it to behave like Vec (which is covariant over its T).

SmallVec v2 (currently alpha) changes the design in a way that avoids this, but until it stabilizes I wrote the covariant-vec crate as an alternative.

The same projection pattern also affects Cow<'a, B>: it is covariant over 'a, but invariant over B because of <B as ToOwned>::Owned. Others have already built the cow2 crate to address that case.

Have you run into other situations like this in your daily work—types where an associated-type projection accidentally introduces invariance? Maybe it would be useful to start a public catalog of such cases and discuss possible patterns/workarounds. I’d be happy to help get that going.

Thanks for sharing this! This is a perfect example.
It looks like that issue has been open for quite a while without a clear timeline for a fix in std. Should we consider writing a community crate that provides covariant alternatives (e.g., a covariant Lines iterator) to tide people over until the upstream Pattern API is fixed?

I'm afraid I can't give a solid answer/opinion at the moment. Projections are invariant for good reasons (there's no way to require a covariant (or contravariant) type at the type/trait system level), and I haven't evaluated the approaches in the cited crates to formulate an opinion on their soundness and/or how likely those approaches would be for forever-stable std.

I agree that these crates probably aren't a good fit for std as things stand. A proper type-system solution, such as variance bounds, would be preferable to working around the limitation with unsafe.
That said, there's still a clear use case for opt-in crates like these. For instance, people trying to use invariant types (like str::Lines) with libraries like yoke currently hit a wall. They need a practical workaround today.
The internals of covariant-vec and cow2 do rely heavily on unsafe to manually manage layout and variance, but the public APIs remain entirely safe. As with most things in Rust, encapsulating the unsafe and proving its soundness is half the battle.

I recently came across a clever language-level workaround for this issue, which also helps explain why the compiler treats these two cases differently.

Consider a struct that directly uses an associated type projection in its field:

trait WithAssoc { type Assoc; }

struct Holder<W: WithAssoc> {
    foo: W,
    bar: W::Assoc, // Associated type projection in a field
}

This is invariant over W, so the function fn invariant<'a: 'b, 'b>(x: Holder<ImplsAssoc<'a>>) -> Holder<ImplsAssoc<'b>> does not compile.

However, if we decouple the associated type into a separate generic parameter and only use the associated type as a bound, the struct becomes covariant:

struct CovariantHolder<W: WithAssoc<Assoc = Assoc>, Assoc = <W as WithAssoc>::Assoc> {
    foo: W,
    bar: Assoc, // Plain generic parameter in a field
}

Now fn covariant<'a: 'b, 'b>(x: CovariantHolder<ImplsAssoc<'a>>) -> CovariantHolder<ImplsAssoc<'b>> does compile. The key is that the compiler now sees a plain type parameter Assoc in the field, and can apply normal variance rules to W and Assoc separately. The associated-type projection only appears in a where bound, where variance is not computed.

This is a clever trick, but it does have downsides: it adds an extra type parameter to the struct, which can pollute the public API and require callers to specify it explicitly in some cases.

If we're willing to decouple the associated type into a generic parameter, we can pleasantly bypass the invariance issue entirely—without any unsafe blocks!
Well... I don't really expect this trick to be accepted by std though. It seems to introduce a ton of API noise.
Oh well...