1

I have a struct with a generic type that needs to implement a lot of traits, and it's making my code very frustrating to read/write because I need to include those constraints in so many places. Here is an example:

use std::fmt::*;
use std::ops::*;

pub struct MyStruct<T: Copy + Clone + Display + Debug + Neg + Eq + Ord + Cmp> {
    //...
}

impl<T: Copy + Clone + Display + Debug + Neg + Eq + Ord + Cmp> MyStruct<T> {
    //...
}

impl<T: Copy + Clone + Display + Debug + Neg + Eq + Ord + Cmp> Ord for MyStruct<T> {
    //...
}

impl<T: Copy + Clone + Display + Debug + Neg + Eq + Ord + Cmp> Neg for MyStruct<T> {
    //...
}

I haven't tried to compile this example so I may have made mistakes in it, but I think it adequately demonstrates the problem. Is there a way to write this in a way where the type constraints only appear in one place?

Lionel Foxcroft
  • 1,584
  • 3
  • 9
  • 23
  • 1
    You should avoid putting constraints on the struct and instead put them on the `impl`s and methods as required. – kmdreko May 01 '21 at 23:10
  • 1
    or perhaps this is really what you want and just need a *supertrait*? [Is there any way to create a type alias for multiple traits?](https://stackoverflow.com/questions/26070559/is-there-any-way-to-create-a-type-alias-for-multiple-traits) – kmdreko May 01 '21 at 23:12
  • That is an improvement in some cases, but some traits can't be left out of the struct declaration. For example, you can't derive Copy if it's not implemented on all members. Even ignoring that, lots of traits still need to be included on all the `impl` blocks because of how frequently they are used. – Lionel Foxcroft May 01 '21 at 23:13
  • Yup, that's what I'm looking for. I didn't realize traits could inherit from other traits, that completely solves my problem. Thanks! – Lionel Foxcroft May 01 '21 at 23:14

0 Answers0