genericsrust

Is there a way to define a generic type generically?


If I want to implement a struct with a certain generic type that requires alot of traits, like below. I then have to copy this to every time i implement a trait for this struct (where it needs the same type) is there a shorthand way to do this? I am imagining something like generic T = Add + ... + PartialEq

impl<T> FOO<T>
where
    FE: Add
        + Copy
        + ...
        + Debug
        + PartialEq,

I've tried looking for this on the web to no avail, however I am also very new to rust so it may be obvious, sorry if this is the case.


Solution

  • You can create a new trait, which has all your required traits as supertraits, and then use blanket implementation. For example:

    trait Combined: Copy + Clone + Debug + Display /* add how many of these you want */ {}
    
    impl<T> Combined for T where T: Copy + Clone + Debug + Display {}
    
    struct Foo<T: Combined>(T);
    
    impl<T: Combined> Foo<T> {
        //
    }
    

    Note however, that it is idiomatic to leave trait bounds when declaring structs (unless you have to name associated types of those traits), and only put bounds on impl blocks. Still this technique allows to greatly simplify naming complex bounds.