Why can't type aliases be used for traits?


I’ve got a function for which the ‘where’ clause started to get complex. In particular, there was a where F: FnMut(u8, u16, &str). This particular signature was being used in a number of places. So I refactored it into a type alias: pub type Some = FnMut(u8, u17, &str). Good practice and all that. But rustc doesn’t like it, moaning about type aliases cannot be used for traits. Why? Is there some edge case that makes this difficult?

This seems to violate the principle of least surprise. As a moderate rust user, this is a consistent experience for me. Perhaps I’m not just not tuned into the ‘rust’ view of the world.


There are somewhat nontrival implications to worry about - there’s an RFC proposing a way forward here: https://github.com/rust-lang/rfcs/pull/1733


Thank you. Looks like something might happen in the future. I particularly appreciate @withoutboats observation in that RFC “I want these for situations where I have extensive and repetitious bounds in my abstract library code, not to shorten the traits I’m actually impling (sic)”. This is exactly what’s going to happen in my current code to fix this, retarding substantially communication of meaning and its longer term maintainability.

As for me, it seems I misconstrued type aliases as just aliases (a sort of macro expansion or search and replace in my head), without the nuances.


A workaround, which is admittedly far from ideal, is to create a new empty trait which inherits all the bounds that you need, and implement it for each type which you care about:

trait CompositeTrait: Trait1 + Trait2 + Trait3 {}

impl CompositeTrait for Type1 {}
impl CompositeTrait for Type2 {}
impl CompositeTrait for Type3 {}


I thout you could make a type macros, but I culd not get it working.


Yes, that’d work. In many ways, it’s really not that different to how we used to do this in Java… create an interface with one method on it and implement it… of course, that’s boxed, but it gets the job done with a lot less friction and substantial readability. A real boon, not least when the new guy on the team is refactoring on the codebase…