0

My method needs both of its generic types to have the same trait bounds, is there any way to write it without repetition?

fn value(&mut self, arg: U) -> V 
    where
    U: std::cmp::Eq + std::hash::Hash, 
    V: std::cmp::Eq + std::hash::Hash, 
{
JanMaslo2
  • 68
  • 1
  • 4

1 Answers1

1

You cannot alias trait bounds, but you can create a trait with some supertraits, and add a blanket implementation:

// You can only implement Foo on types that also implement Debug and Clone
trait Foo: Debug + Clone {}

// For any type that does implement Debug and Clone, implement Foo
impl<T> Foo for T where T: Debug + Clone {}

With those lines, you now have a new trait Foo, which is automatically implemented for any type that is also Debug and Clone. Then you can use Foo as your trait bound, and it will act as if you had written: T: Debug + Clone

David
  • 453
  • 3
  • 7
  • 20
cameron1024
  • 9,083
  • 2
  • 16
  • 36