Search code examples
genericsrusttraitsrust-macros

Specifying generic parameter to belong to a small set of types


Is it possible with to constrain a generic parameter to be one of the select few types without figuring out what traits precisely define those type? e.g.

impl<T> Data<T> where T == u32 || T == u64 

Sometimes it's tedious to figure out what all traits to add to where to get the types you want, and sometimes one wouldn't want to allow a type even when it makes syntactic sense because of semantics.


Solution

  • You could use a marker trait for the types you want to support:

    trait DataSupported {}
    
    impl DataSupported for u64 {}
    impl DataSupported for u32 {}
    
    impl<T> Data<T> where T: DataSupported {}
    

    As Pavel Strakhov mentioned, if you need to use this trait for a few impls and you need other trait bounds, then you can just make those traits as bounds of your marker trait instead, which will keep your impls terse:

    trait DataSupported: Num + Debug {}