3 ms·
I agree with him though that enum variants not being distinct types is a hassle. I think there's an RFC for making this possible.
by the_duke 10y ago
I agree with him though that enum variants not being distinct types is a hassle.
I think there's an RFC for making this possible.
- lmm 10y agoIt's by design AIUI; certainly it's often what you want (I won't claim "always", but probably more often than actually wanting the distinct subtypes).
- gamegoblin 10y agoEven Haskell needs an explicit language extension flag to make this happen (-XDataKinds I believe). Consider this use case data Pointer = NullPointer | NonNullPointer Int And I want a function that only accepts non-null pointers: dereference :: NonNullPointer -> a To do that and maintain my Pointer type, I'd have to do something like: data NonNullPointer = NonNullPointer_ Int data Pointer = NullPointer | NonNullPointer NonNullPointer -- ^ The namespace of constructors and types is distinct, -- so this is fine and is a constructor of Pointer that -- contains a NonNullPointer, which only -- has one constructor, NonNullPointer_ (note the _) I believe -XDataKinds does something like this behind the scenes, but someone better than I should verify. I just use the above technique rather than questionable language extensions.
- dllthomas 10y agoDataKinds lets you use NullPointer and all the various NotNullPointer values as types, but they are uninhabited. It doesn't (obviously) let you restrict a parameter to values using a particular constructor of a sum type.
- gamegoblin 10y agoJust looked it up and it was GADTs I was thinking of that would allow me to do something like that.
- dllthomas 10y agoAh, yes.
- saosebastiao 10y agoThis is one of my last remaining nitpicks with Rust as a language. In Scala, sum types are a form of sub-type polymorphism, where each variant is its own distinct type and can be used as such. To get similar behavior in Rust, you end up having to wrap structs in the variant like this: struct Foo_ enum Bar { Foo(Foo_) } It works, but it is extremely annoying.