Skip to content

Type covariance absent when used in struct #1610

Description

@space-elephant

Arrays are covariant, but structs containing them don't seem to be. If I create a struct

struct Test<T> (ndarray::Array2<T>);

then, even though Array2 is covariant over T, my struct isn't:

// works
pub fn covariant<'long: 'short, 'short>(input: Box<ndarray::Array2<&'long u8>>) -> Box<ndarray::Array2<&'short u8>> {
    input
}

// compiler error
pub fn invariant<'long: 'short, 'short>(input: Box<Test<&'long u8>>) -> Box<Test<&'short u8>> {
    input
}

This doesn't make sense to me. From the rust reference, I would expect Test's variance to depend only on the types of its field, but it doesn't. Moreover, only structs that internally contain Array2 are affected: structs that take the array as a parameter (like the Box above) are fine, as are tuples and rust arrays. This is also unaffected by the complexity of the type inside the array, as long as it references a lifetime.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions