7

I have a trait which only has one requirement, the presence of a methods len(&self) -> usize. It then provides implementations for a couple of new methods for the struct.

trait MyTrait {
    fn len(&self) -> usize;

    // ... some new functions with implementations
}

I'd like to implement this trait on std::collections::LinkedList which already has a method with that exact type signature. Currently, I'm doing this:

impl<T> MyTrait for LinkedList<T> {
    fn len(&self) -> usize {
        self.len()
    }
}

I can then use the new methods defined by MyTrait on my LinkedList instances. However, it feels unnecessary to have to repeat the definition of the method like this, since the type signatures are identical. Is there a way to omit the re-definition of len in my trait implementation?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78

1 Answers1

7

Is there a way to omit the re-definition of len in my trait implementation?

No, it is not possible.

You may be able to write a macro of some kind to write the code for you, but dealing with type parameters is annoying, to say the least.

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Ah OK; thank you for your answer. I'd consider writing a macro if I needed to implement this trait more, but since it'll only be for `LinkedList` I won't bother. Thanks again – Aaron Christiansen Dec 10 '18 at 20:49