Generic Traits with Output

I have a collection of generic functions of the following form:

fn square<T>(i: T) -> T 
where 
	T:std::ops::Mul + std::ops::Mul<Output = T> + Copy {
	i*i
}

since the number of types of this collection has gotten longer I would like to collect them in a name that can be curated at one position in the code; for the normal traits that works fine, eg:

trait TraitCollection: Debug + std::ops::Mul {}
impl<T: Debug + std::ops::Mul> TraitCollection for T {}

TraitCollection now has all methods of Debug and std::ops::Mul. But how do I incoroporate std::ops::Mul<Output = T> in this?

You can use Self to refer to the type implementing the trait.

1 Like

Sorry something must have gotten wrong when typing

The last time I tried typing something like this I got compiler errors (I did not investigate further because I did not expect it to work)

Solution (plus some other traits that were necessary)

trait TraitCollection: Debug + std::ops::Mul + Sized + std::ops::Mul<Output = Self> + Copy {}
impl<T: Debug + std::ops::Mul + std::ops::Mul<Output = Self> + Copy> TraitCollection for T {}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.