'How can I specify the same trait bounds on two generic types? [duplicate]

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, 
{


Solution 1:[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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cameron1024