I do not know everything about every computer language, or even every one I write about on this site. Instead, I learn as I go along. From other languages like C# I was familiar with the concept of enums—types that store known values and can be referenced by name.
But in Rust, enums have an additional feature—they are an algebraic data type. This means a value in an enum
can reference some data—like a struct
instance, a String
, a tuple or a number.
In practice, this means we can use a single enum to refer to multiple data types:
enum
with two variants, each with a different data type, can be tested in a match
statement and we can evaluate the data at runtime.enum
instance will have until runtime.So we can create a Color
, and it could have a value of Red
with a String
, or a value of Blue
with a usize
instead. And we can refer the Color
as meaning either Red
or Blue
—and a String
or usize
only in appropriate cases. This can simplify some programs where we must return many types of data from a single function.