r/rust•
CrystalDev

Passing Generic Type as Type Parameters

Hello everyone,

I hope this is not a stupid question but I was wondering about the following.

I'd like to achieve the following:

struct MyStruct<A, B, C, M> { map: M<A, C<B>>; }

Such that I can do something like: MyStruct<i32, i32, Vec, HashMap>. The idea is that the user of the struct is able to pick the map and collection that is most efficient for his uses.

For as far as I know we cannot pass generics as Type Arguments. Is there any way around this without too much overhead?

Posted Oct 15, 2018, 6:00 AM UTC

1612
PthariensFlame•

The general feature you're looking for is called higher kinds, and Rust is hopefully getting a version of them soon (in the form of generic associated types, or GATs for short). Today, however, you can't write this code. :(

15
etareducerust · lang-team•

(Do note that GATs do not amount to quantification over type constructors, so it does not introduce higher kinded type polymorphism; however, you get much of the same power - but not ergonomics...)

6
CrystalDevOP•

Thanks for your replies! I will look into this :) Do you believe GATs still needs a lot of time before it enters the language?

1
Programmurr•

Is this intended to replace PhatomData?

1
PthariensFlame•

No, PhantomData is completely unrelated to this.

1
newpavlovrustcrypto•

One possible workaround is to write code like this:

trait Map<K, V> { }

struct MyStruct<K, V, C, M>
    where M: Map<K, C>, C: IntoIterator<Item=V>
{
    map: M,
    _col: PhantomData<C>,
    _key: PhantomData<K>,
    _val: PhantomData<V>,
}

Here Map is a custom trait which will generalize required map behavior. The main drawback is that you'll have to duplicate types, e.g. MyStruct<i32, u32, Vec<u32>, HashMap<i32, Vec<u32>>>.

9
CrystalDevOP•

Thanks! I'll probably resort to this for now and use an alias :)

1
Omniviral•

The workaround would be have C and M be concrete collection and map type. Then in implementation you add bounds to to ensure C is collection over B and M maps A to C.

3
barskern•

I don't know if it's this you're searching for, but have you seen how specs does something similar to what you describe using associated types?

1
CrystalDevOP•

I haven't seen specs yet, do you have some concrete place to look within the project?

1
barskern•

The following example is taken from the README.md, and there is a chapter in the book that explains storages.

#[derive(Debug)] 
struct Pos(f32);

impl Component for Pos {
    type Storage = VecStorage<Self>; 
} 
2
CrystalDevOP•

Very interesting what they do here! Thanks!

2