I have a lot of type constraints, and I would like to make it more readable. For example, is there a way to simplify this:
<P: Serialize Clone Eq std::hash::Hash std::fmt::Display, E: Serialize Clone Eq std::hash::Hash std::fmt::Display>
Can I remove this duplication somehow, maybe with a where
statement to make it something like this:
where P E: Serialize Clone Eq std::hash::Hash std::fmt::Display
It just seems wrong to have it so large.
CodePudding user response:
There's not currently any way to combine type constraints like you're hoping for. However, you can at least consolidate the boilerplate a little bit by defining your own trait and a blanket implementation, like this:
trait Data: Serialize Clone Eq std::hash::Hash std::fmt::Display {}
impl<T> Data for T where T: Serialize Clone Eq std::hash::Hash std::fmt::Display {}
This will then allow you to write type constraints like this:
where P: Data, E: Data
Note that the original type constraints must still be replicated on both the trait definition and the implementation, to ensure that 1. types implementing the trait also expose the necessary behavior, and 2. the implementation only applies to types that implement the necessary traits.