Partially Applied Types

Consider that I want to write a piece of code that is generic over the type of lock it should use (bear with me here, think spinlock vs blocking mutex). So there is a trait:

trait SomeLock<T> : From<T> {}

Now I want to write a function that takes a lock implementation as type parameter. The user doesn't know what the lock is for so they cannot fully specify the type. As a user, want to be able to say:

generic_code<SomeMutex>()

Note the missing type argument to SomeMutex. Is this actually possible in Rust? In generic_code, I would want to write something like this:

fn generic_code<Mtx: SomeMutex<_>>() {
  let serialized_int = Mtx::from(17);

 ...

}

This needs a feature called higher kinded types, which rust doesn't support, however it can emulate them with the generic associated types feature, which is currently available in nightly.

#![feature(generic_associated_types)]

trait SomeLock<T> : From<T> {}

trait SomeLockGAT {
    type Lock<T>: SomeLock<T>;
    
    fn from<T>(t: T) -> Self::Lock<T> {
        Self::Lock::from(t)
    }
}

fn generic_code<Lock: SomeLockGAT>() {
  let serialized_int = Lock::from(17);
  
  // ...
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.