Conditions on &Self for trait


I want to define a trait for types that support both

Self: Mul<Self, Output = Self>
&Self: Mul<&Self, Output = Self>

The reason that I want the second one (with references) is to avoid a bunch of call to clone. I tried to add a where clause to my trait, but I have lifetime problem with the references.

Any idea how to achieve that or anything similar?

Rust wants you to clarify that you want that to hold for any lifetime:

trait MulGroup: Sized + Mul<Self, Output = Self>
where for<'a> &'a Self: Mul<&'a Self, Output = Self> {}
1 Like

You need to declare a lifetime, like you would on a function declaration with explicit lifetimes. Inside of where clauses, this is done with the for keyword:

where for<'a> &'a Self: Mul<&'a Self, Output = Self>
1 Like

Thanks, this indeed work well. However, it seems that anytime I want to use the trait, I have to do

T: MulGroup,
for<'a> &'a T: Mul<'a T, Output = T>

Is there a way to declare that MulGroup implies Mul for references?

No; the compiler is currently capable of “elaborating” trait bounds of the “supertrait” form Self: Mul... but not anything without plain Self on the left side, like &Self: Mul....

1 Like

Ok. Thank you. I will take a look at that thread.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.