Implementing trait which has a generic type

I have a trait which looks like this

trait Trait<T>{
  fn foo(arg: T) {}
  fn bar(arg1:i32, arg2:T) {}
}

and I want to implement this trait for a type. and I want to do it something like this

struct Baz;
struct Abcd;
impl<T> Trait<T> for Baz where T is Abcd {
.....
}

With this I can avoid specifying Abcd in foo & bar . this makes easier for me if I want to change Abcd to xyz . How should I impl this trait

trait Trait<T>{
  fn foo(arg: T) {}
  fn bar(arg1:i32, arg2:T) {}
}

struct Baz;
struct Abcd;
impl Trait<Abcd> for Baz {
  fn foo(arg: Abcd) {}
  fn bar(arg1:i32, arg2: Abcd) {}
}

If you want to reduce the boilerplate because you'll implement it for several types, you should use an associated type rather than a generic type argument.

2 Likes

This makes changing the type a one-line change...

type TraitParamForBaz = Abcd;
impl Trait<TraitParamForBaz> for Baz {
    fn foo(arg: TraitParamForBaz) {}
    fn bar(arg1:i32, arg2:TraitParamForBaz) {}
}

...except fixing all the other code that uses the implementation.

1 Like