Grouping traits

Hello,

I have a few functions with generic argument and they all needs T: PartialEq + Clone + Default. I got lazy to type it every time and I realized that I can give it name:

pub trait MyTraitGroup: PartialEq + Clone + Default {}
impl<X> MyTraitGroup for X where X: PartialEq + Clone + Default {}

and then I can just use it T: MyTraitGroup.

Could you please tell me is that a known pattern or am I doing something stupid that will byte me later?

Thank you.

If/when trait aliases become a thing, you could rely on that.

Could you please tell me is that a known pattern or am I doing something stupid that will byte me later?

While I don't encounter it often, it's definitely a thing. For example, serde::de::DeserializeOwned exists for similar reasons. It's not "stupid" even if I personally prefer the somewhat painful process of just copying/pasting the trait bounds that way downstream code doesn't have to take the time to see what this "dummy" trait is all about. You said "a few functions" which to me means "around 3", so I don't think it makes much sense.

If you are making this part of your public API, then I'd name it more appropriately though that way a reader can reasonably "guess" what it's all about.

2 Likes

It's 6 functions and it is not public. But I take your point! Thank you.

Also, if the functions are not free; then just have a single impl block with those bounds. For example:

impl<T: Clone + Default + PartialEq> Foo<T> {
    fn bar<T>(&self, x: T) {}
    fn fizz<T>(&self, x: T) {}
}

it is not public

Then why is the trait defined to be pub? If it's not public, then I think it matters even less. If it makes it easier for you to maintain, then knock yourself out.

1 Like