Type covariance absent when used in struct

Open
#1,610 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
48/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Quiet
Tech stack
rust
Domain
data

Research direction

Start with the reported Test struct and the covariant and invariant function examples in this issue. Compare variance behavior for Array2 fields with Box, tuples, and Rust arrays; done means identifying and correcting the discrepancy and adding a regression test for the lifetime conversion.

Written by the indexing model from the issue text.

Description

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.

Dominant language
Rust
Stars
4.3k
Forks
391
PR merge metrics
No merged PRs in 30d

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from rust-ndarray/ndarray

All issues in rust-ndarray/ndarray

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.