rust-lang / rust-lang/rust

Struct containing only associated type of generic may be too constraining variance wise

Open
#140,109 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-variance C-discussion T-types
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

The following code is currently rejected by the compiler, because sub-typing for S is taken on the whole T and not only its associated type. Maybe this is something that could be improved?

trait TraitAssoc {
    type Assoc;
    fn assoc(self) -> Self::Assoc;
}

impl<T> TraitAssoc for &T {
    type Assoc = ();
    
    fn assoc(self) -> Self::Assoc {
        ()
    }
    
}

struct S<T: TraitAssoc> (
     T::Assoc
);

impl<T: TraitAssoc> S<T> {
    fn new(x : T) -> Self {
        Self(x.assoc())
    }
}

fn maybe_could_compile() {
    let v : Vec<u8> = vec![];
    let s = S::new(&v);
    drop(v);
    drop(s);
}

This also happens with nex-gen trait solver AFAICT.

Contributor guide

Open the contributing guide

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.

Research direction

Start by compiling the Rust reproducer in the issue and examining how the compiler applies subtyping and variance to S when its field uses only T::Assoc. Compare the behavior with the stated associated-type expectation; done means the intended behavior is decided and the example has a clear compiler outcome, with coverage added if the project identifies an appropriate test location.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.