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.

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

    Issue actions