sciencenotes.medium.com 3 min read Original Source

3 Fundamentals of Enums in Rust

In Rust Programming For Beginners, I introduced Enums in Rust. In this tutorial, I explain three fundamental points of Enums:

  • Option Enums
  • Additional data in Enums
  • Result Enums

Recall from Rust Programming For Beginners, EyeColor is an enum for different color of eyes,

[Embedded content: d4ea8f9018ae13879979da468b13e7b9]

User is a struct for user information,

[Embedded content: f3f57b622fbaf70141f9d563330d08f0]

and bmi() is the function that computes the Body Mass Index of a user.

[Embedded content: 09795576994723e3b5701a1540ce5dad]

In this tutorial, we aim at developing these examples with some new knowledge.

1. Option enum

In the user structure, eyecolor and country sound irrelevant information for computing BMI. Therefore, we would like to make them optional. This way, user does not have to provide such information.

Option enum enables us to create optional data. In this case, we get “some” data or no data. It defines like this:

[Embedded content: 54ca5327f6aef79149437cfd47a101f1]

<T> means if there is some data, it should have some specific type. Otherwise, we have no data or None. Therefore, the user structure is changed to:

[Embedded content: 966a4cde11b6b5ccbd4c02f8346c50c3]

Similarly, the function’s output could be optional. If it is not nessecary for a function to return “some data”, the output is option<T>.

For example, the eye_color() function takes a borrowed string as an input and returns an option; it returns some EyeColor if the string matches to one of the EyeColor‘s variants or None if it doesn’t.

[Embedded content: ff36be11ef98b17479d5622a9fe9130a]

1.1. Option Combinators

Option combinators make manipulating and managing option enums easy. In this section, I introduce some handy functions used for option data. Read more about option combinators in the Rust documentation for option data.

  1. is_some() checks if the option is some data or not.
  2. is_none() checks if the option is None or not.
  3. unwrap() takes out the data if there is some data. Otherwise, it raises an error: thread 'main' panicked at 'called 'Option::unwrap()' on a 'None' value'
  4. map(closure) transforms option data if we have “some” data by a function (closure). When option data is None, nothing happens. It is handy because there is no need to check if we have some or no data.
  5. filter(closure) filters option data by some condition which is a function with a single argument that returns a boolean.
  6. or_else(|| Some()) returns some default value if the option data is None. If the option data is something, it does nothing.
  7. unwrap_or_else(|| <>) is similar to or_else(). The difference is or_else() returns optional data, but unwrap_or_else(|| <>) returns the data. In other words, it unwraps or_else() the result.

In the following example, I’ve created an Optional float called height. Using map(), I transform the height from centimeter to meter and check if it is greater than 1 or not. In the last part, I unwrap the height.

[Embedded content: 7eac0583b3fad07a008a3ec6af77ac82]

Note: filter() borrows the number. So, we should borrow 1 inside the condition: filter(|a| a> &1.)

2. Additional data in Enums

Consider we want to add gym name to our user structure. To do so, we have a list of gym names we are interested in more. To do this, we create another enum.

[Embedded content: 3400bbe66990f8d4494ee1fdcca44df0]

If users are a member of the FitStar or McFit, we are interested in their membership ID. Otherwise, we are not.

One solution is to create a structure with two variants and make membership ID optional:

[Embedded content: adf1d615028bba5823aba632b32aab9b]

Yes, this works. But there is more we can do with enums in Rust. Enum in Rust is not limited to plain variants, but it can have additional data. For example, Fitstart(Membership_ID). Hence, a better solution is:

[Embedded content: 3485e61c21434c8ad5cd9c53439861e1]

This way, instead of creating an enum and a struct for only one entity of the user struct, we could create one enum with additional data for each variant. Doing so, the user struct is changed to:

[Embedded content: 966a4cde11b6b5ccbd4c02f8346c50c3]

3. Result enums

In this part, we want to enrich our BMI function.

A function can return a result or error. Most of the time, we should take care of special cases in a function. If the function refuses to handle some cases, it raises an error. In this matter, Rust Result enums are defined by:

[Embedded content: 3c4a5d5cd7ed111bfbb3e769d4fd6b69]

In the current bmi() function, if the user inserts a negative value or zero for the weight, BMI becomes negative or zero, which does not make sense. To prevent this, bmi() raises an error to tell the user that the weight is invalid. In this example, the error could be a message for the user.

Therefore, we change the bmi() function in such a way it returns an error message when the weight or height is negative or zero. Otherwise, it computes BMI and returns a float.

[Embedded content: e35362a0094be43ea3fee928eb4be924]

3. 1. Result question mark operator

The basic way to find out if a function’s output Result is Ok or Err is to do a match over it. For example:

[Embedded content: e35362a0094be43ea3fee928eb4be924]

However, there is a shorter way to do this. Question mark operation is a shortcut to work with Result enum. If a function returns an OK result, a question mark catches the result.

[Embedded content: c30efcafc82460459eb20856eebe1bc2]

Note: use the question mark operation inside a function that returns a Result enum. Otherwise, you face a compilation error: cannot use the '?' operator in a function that returns '()'

Summary

In this tutorial, I explained three types of Enums in Rust. The first was Option Enums to create optional data. The second was the extended type of Enums that contains additional data for enum’s variants. And the third was Result Enums for error handling of function.

To summarize what we learned in this tutorial, go line by line of the following code to review all you learned in this tutorial 😊.

[Embedded content: abcab9467e35ce8e9e1a8741ca9d039d]

In the next tutorial, I plan to write about closures, iterators, traits, and modules in Rust, so stay tuned 😊.

Arun Mathew Kurian, Abhishek Gupta

Join Medium to read great tutorials and stories!
I write Machine Learning, Deep Learning and Data Science tutorials. Upgrade to read more…