52

Is there a way to combine multiple traits (by inheritance?) in order to define a new trait? I'm looking for something like concepts in C++:

auto concept newConcept<typename T> : concept1<T>, concept2<T>, concept3<T> {};

Suppose I want to make a new trait that inherits from Clone, Default and some other traits, is that possible?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
BigEpsilon
  • 579
  • 1
  • 4
  • 7
  • I was searching for a question like this under the term "super traits" so I just comment it here and hopefully someone may find it with this term later. – fuma Nov 25 '21 at 11:49

1 Answers1

83

Yep!

trait NewTrait: Clone + Default + OtherTraits {}
impl<T> NewTrait for T where T: Clone + Default + OtherTraits {}
Darrien
  • 71
  • 2
  • 12
sfackler
  • 1,130
  • 8
  • 4
  • 1
    Thanks (tried this with commas... but it didn't work). I searched for this for a long time, too bad it is not in the guide. – BigEpsilon Nov 17 '14 at 22:58
  • 1
    It is mentioned in the reference, though: http://doc.rust-lang.org/reference.html#traits Yeah, I tripped up on this as well :) – Subhash Nov 18 '14 at 01:28
  • 2
    You can write a macro trait_alias as described in http://stackoverflow.com/questions/30291584/macro-for-defining-trait-aliases – malbarbo May 03 '16 at 17:44
  • This is called a blanket implementation https://users.rust-lang.org/t/what-are-blanket-implementations/49904 – debuti Sep 28 '22 at 16:39