Posts

Showing posts with the label rust

Lifetimes in Rust

Image
One of the (or maybe just   The ) coolest part of #Rust is the concept of   Lifetimes  — the scope for which a reference in Rust is valid. Or, to put it differently think of a “Lifetime” as the range between when any data is introduced into a program (“initialization”), and and when it is removed (“dropped”). (•) You’re probably thinking “garbage collection”, and you wouldn’t be entirely wrong. OTOH, you wouldn’t be right either — Lifetimes are embedded deep into Rust (e.g., they are part of function signatures, references are annotated with their lifetimes, etc.). Think of this as the compiler actively validating all uses of the data   before   you even run the program, and ensuring that whenever data is “borrowed” it can’t live longer than the reference it is borrowed from For an excellent description of lifetimes, take a look at Florian’s writeup at   https://goo.gl/A7crBV , and then read up on the — very clear! — documentation at   https://goo.gl/...

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 ...