Rust, Software Development

Enum Variants And Match Expressions In Rust

There are a few ways to define an enum variant and, as a result, to use it when creating match expressions. We can define a variant in three ways –  one-word, Tuple-like, or Struct-like.

Match One-Word Enum Variants

Let’s say we want an enum based on the days of a week, as shown below. Each variant is case-sensitive and represents a day in a week.

To use the variants with the match keyword, we construct match expressions as follows. There are only six match expressions for seven days – one expression matches for Saturday or Sunday!

We don’t have many options for this type of variant. For each expression, we can only use the variant itself or the OR (|) operator to specify multiple variants.

The codes output the following.

Match Tuple-Like Enum Variants

We can also create enum variants like tuples and use them in match expressions differently from the previous examples.

The codes output the following.

Struct-like Enum Variants

Another way to create variants is by defining them like structs. How we use them with match expressions is somewhat similar to tuple-like variants.

Each struct-like variant can vary from the other variants.

The codes output the following.

Mixed-Style Variants

In Rust, we can use different styles of variant creation within the same enum. Consider the following codes.

Now we have a one-word January, the tuple-like October, and the rest of the variants are struct in form.

The codes output the following.

We tested the codes using Rust 1.42.0.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like