Sum Types! Get your Sum Types here!
Sum Types — or, more to the point, Algebraic Data Types (•) — are one of the cooler things in Rust (••). Long familiar to folks in the Haskell / OCaml (and other ML-derived languages), they are, at heart, fairly simple things. In short, a “sum type” is any type that has many possible representations. e.g. in Haskell, if you wrote data Bool = False | True you’d basically be saying that Bool could take the values “False” or “True”. Extending this, if you wrote (in Haskell again!) data Event = ClickEvent Int Int | PaintEvent Color you’d be saying there is a data type Event that contains two cases: it is either a ClickEvent containing two Ints or a PaintEvent containing a Color. It’s the kind of thing that is ridiculously useful, and impossible to live without once you’ve had it. By the way, these tend to go by a bunch of different names — tagged union , variant record , disjoint union , and a whole host more. Chad Austin has an ...