Skip to content

Type parameters can be constrained only as an associated type #26262

Closed
@arielb1

Description

@arielb1

You can create an inherent impl where the impl substs are not constrained by the impl signature. If the parameters are constrained by the method signature, you can even get code that usefully runs (otherwise you get "can't resolve" errors):

struct S<T>(T);

trait Tr { type Assoc; fn test(); }

impl Tr for u32 {
    type Assoc = u32;
    fn test() { println!("test for u32!"); }
}

impl Tr for u64 {
    type Assoc = u32;
    fn test() { println!("test for u64!"); }
}

impl<T: Tr> S<T::Assoc> {
    fn foo(self, _: T) {
        T::test();
    }
}

fn main() {
    <S<u32>>::foo(S(4u32),4u32);
}

Note that you need to use UFCS notation to avoid #25679 (which is an issue with method lookup).

RFC447 is silent with regards to this issue, but this allows you to create an impl that is not resolvable by its trait-ref.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions