How can I name a set of type bounds?

Viewed 132

If I have a long list of type bounds that must be repeated in many places, how can I give them a name?

For example, what if instead of:

fn foo<T: Thing>(t: T) -> T
    where T: Copy, T: Debug { ... }

I want to write:

fn foo<T: Thing>(t: T) -> T
    where T: CopyDebug { ... }

where CopyDebug is defined to be Copy+Debug?

2 Answers

If you are using nightly Rust, you can use the nightly feature trait_alias (https://doc.rust-lang.org/unstable-book/language-features/trait-alias.html)

trait CopyDebug = Copy + Debug;

And then any type satisfying both Copy and Debug will also satisfy CopyDebug automatically.

Because this feature is nightly, you need to put #![feature(trait_alias)] at the top of your crate main file.

You can combine a list of type bounds into a single trait by creating an empty trait that requires the full list of type bounds on its implementer, like this:

trait MyCombination: A + B + C + D {}
impl<T: A + B + C + D> MyCombination for T {}

So in the case of CopyDebug, you can write:

trait CopyDebug: Copy + Debug {}
impl<T: Copy + Debug> CopyDebug for T {}
Related