Home
Blog
Advantages of Enums in Rust
Updated
Dot Net Perls

Advantages of Enums in Rust

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:

An 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.
We do not need to know which kind of attached data an enum instance will have until runtime.

So we can create a Color enum, 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.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
An RSS feed is available for this blog.
Home
Changes
© 2007-2025 Sam Allen