3 ms·
Is there any way to use GATs to achieve a particular use case of ah-hoc/anonymous enums[0]? Say if library L1 returns enum A|B, L2 operates on enum A|B, and mai
by karmakaze 4y ago
Is there any way to use GATs to achieve a particular use case of ah-hoc/anonymous enums[0]? Say if library L1 returns enum A|B, L2 operates on enum A|B, and main wants to pass enum A|B from L1 to L2, with the kicker being A, B are concrete in main.
I'm not interested in distinguishing between multiple appearances of the same type as in the RFC example, so rather like:
let foo: (~str|int) = (_|666);
match foo {
(s: str|_) => println(fmt!("string: %?", s)),
(_|n: int) => println(fmt!("int: %?", n))
}
The most disappointing thing I've encountered with Rust is not seeing anonymous enums or structural typing other than for tuples. I read somewhere that structural typing is only for tuples because the word struct is in structural(?!).
[0] https://github.com/rust-lang/rfcs/issues/294 https://github.com/rust-lang/rfcs/issues/294
- celeritascelery 4y agoThese are called sub-types or pattern types, and they are not in the language. But they are something I would love to have. You can’t emulate them with GAT unfortunately. https://cohost.org/oli-obk/post/165584-ranged-integers-via https://cohost.org/oli-obk/post/165584-ranged-integers-via
- karmakaze 4y agoI've not heard this called sub- or pattern types before. Perhaps the rfc syntax is complicating the discussion. We have struct and tuple in Rust where tuple is an ad-hoc/anonymous struct where only the number and order of member types matter. We have enum which are nominal types. We don't have the ad-hoc/anonymous version of them where only the set of possible types matter. In TypeScript, F#/OCaml they would be like x: TypeA|TypeB
- celeritascelery 4y agoI first heard about this feature in OCaml. I got the name subtype or pattern type from this thread: https://internals.rust-lang.org/t/thoughts-on-pattern-types-and-subtyping/17675 https://internals.rust-lang.org/t/thoughts-on-pattern-types-...
- karmakaze 4y agoThanks for the reference. I can see how values of type A could be considered as a subset of values of type A|B, but I think the 'any value of type A' subset of type A|B is more related to types and less about restricting the range/set of values for a type.
- hn92726819 4y agoYou might be interested in Rust's either crate (not built-in): https://docs.rs/either/latest/either/ https://docs.rs/either/latest/either/
- karmakaze 4y agoYes, thank you that should work since both libs L1, L2 and main can all refer to Either<A, B>. This parallels a similar solution to the nominal sum types I ended up making for Java (Either<A, B>, Option3<A, B, C>, etc) with these generic types in a common shared library and other libraries and consumers of both accessing the shared type. One more question: In Rust is Either<A, B> type-erased, specializations generated, or something else?