How to create an existential witness type?


#1

I want to use a witness type to enforce invariants of my code, so I’d like to be able to write a function that creates an object with a type in it that cannot match any other type, including the output of the same function called another time.

I’m Haskell I could do this by encapsulating the output in a GADT. Can something like this be done with rust?

The goal here is to create a safe array type with an associated index type, such that the compiler can ensure that you will never encounter an out of bounds error.


#2

The indexing crate achieves this by using invariant lifetimes in a closure to create an effectively existential type. This is probably the best solution that’s possible in rust at the moment. There’s discussion about existential types as it relates to impl Trait syntax, but that’s still ongoing.


#3

Thanks, that is precisely what I was looking for!