Skip to content

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

Open
@krtab

Description

@krtab

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.

Activity

added
needs-triageThis issue may need triage. Remove it if it has been sufficiently triaged.
on Apr 21, 2025
changed the title [-]Struct containing only associated type of generic may be to constraining variance wise[/-] [+]Struct containing only associated type of generic may be too constraining variance wise[/+] on Apr 21, 2025
added
C-discussionCategory: Discussion or questions that doesn't represent real issues.
T-typesRelevant to the types team, which will review and decide on the PR/issue.
A-varianceArea: Variance (https://doc.rust-lang.org/nomicon/subtyping.html)
and removed
C-bugCategory: This is a bug.
needs-triageThis issue may need triage. Remove it if it has been sufficiently triaged.
on Apr 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-varianceArea: Variance (https://doc.rust-lang.org/nomicon/subtyping.html)C-discussionCategory: Discussion or questions that doesn't represent real issues.T-typesRelevant to the types team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @fmease@rustbot@krtab

        Issue actions

          Struct containing only associated type of generic may be too constraining variance wise · Issue #140109 · rust-lang/rust