The rust type system is powerful, but not quite enough (yet)

51 points Unreal_Unreality

Hello fellow Rustaceans,

I've been programming in rust for a couple of years now, and I've done a lot of messing around with type level programming in the last few months, abusing traits as much as I could.

The thing is, all the interesting things that I've been trying to build on stable are blocked behind a good way to check type equality.

It is super easy to make a bound for traits that are equal:

trait IsSame<T> {}
impl<T> IsSame<T> for T {}
[...] where U: IsSame<T>

But it's really hard to make a bound for types that are different. All of my trials ended up requiring something like:

// type level boolean
trait Boolean {} // type level boolean
struct True;
impl Boolean for True {}
struct False;
impl Boolean for False {}

// the trait I want to implement
trait IsEq<T> {
    // for <T as IsEq<T>> this is True, otherwise this is False
    type Eq: Boolean;
}

This would then allow building type level primitives and open the door to so much more. Unfortunately, I haven't found a single way to get this on stable. Think about type level regex compilation, database and query validation, optimized data structures at compile time.

With nightly, we have a few options:

  • Specialization would allow to build this, but the feature is not coming to stable anytime soon (and I don't think specialization is a good idea anyway, but this is subjective)

  • Negative bounds would allow to implement this with the IsSame trait, if the compiler can see that it would lead to all types having the IsEq trait

  • generic const exprs and const type id can also solve this, but these are two features that will require more work and are not coming soon either.

Now, I've been loving rust a lot, but I really feel like there is so much more possibilities with type level programming that is unreachable because of this single missing feature. There have been lots of discussions on this subject (https://github.com/rust-lang/rfcs/issues/1834 for example) and it seems like this is requested by a lot of people.

What is stopping us from having compile time type comparison in the type system ? What are your thoughts on this ?