On Tue, 21 Apr 2015 15:36:27 +0000, Jadbox wrote: > What's the best equivalent to Rust's structural enum/pattern (match)ing? > Is it also possible to enforce exhaustive matches? > Basically, I'm curious on what the best way to do ADTs in D.
std.variant.Algebraic implements ADTs: import std.variant, std.string; struct Foo { ... } alias A = Algebraic!(int, double, Foo); A a = 1; // std.variant.visit enforces that all possible types are handled, so this // is an error: auto res = a.visit!( (int x) => format("Got an int: %s", x), (double x) => format("Got a double: %s", x), (Foo x) => "Got a Foo" ); You can also dispatch to a function with the appropriate overloads/ template instantiations like so: foreach (T; A.AllowedTypes) if (a.type is typeid(T)) myfunc(a.get!T); This also exhaustively guarantees that myfunc can be called with all possible types of a.