One Month Learning Rust - Enums and Pattern Matching

One Month Learning Rust - Enums and Pattern Matching

Introduction

Enums are a well-known data structure that allows defining a type by listing its possible variants. Enums have different syntax and usage in each programming language. In Rust, enums are used quite frequently due to the many benefits they offer.

In today's article, we will explore enums in Rust and see what makes them special compared to other languages.

Enums

An enum is declared as follows:

enum IpAddrKind {
    V4,  
    V6,  
}

The variants can then be used as follows:

let four = IpAddrKind::V4;
let six = IpAddrKind::V6;

Enums in Rust can also store data:

enum IpAddr {
    V4(String),  
    V6(String),  
}

let home = IpAddr::V4(String::from("127.0.0.1"));
let loopback = IpAddr::V6(String::from("::1"));

Additionally, methods can be defined for enums:

enum IpAddr {
    V4(String),  
    V6(String),  
}

impl IpAddr {
    fn call(&self) {
        println!("Hello from IpAddr!");
    }
}

let home = IpAddr::V4(String::from("127.0.0.1"));
home.call();

The Option enum is predefined in Rust and plays an important role in handling null values.

The Option enum has a generic form:

enum Option<T> {
    None,  
    Some(T),  
}

In many other programming languages, null is commonly used to represent the absence of a value. Rust does not have a null value, and in most cases where null would be used, Rust programmers use the Option enum instead.

None represents "no value", while Some represents the existence of a certain data type. For example:

let none: Option<i8> = None;
let five: Option<i8> = Some(5);
let six: Option<i8> = Some(6);

However, direct operations on values of the Option type are not allowed:

// error
let sum = none + five;

// error
let sum = five + six;

So how can we effectively use enums in general and the Option type in particular?

Matching

Matching is a powerful control flow structure in Rust that is used to classify, or match, data and perform actions based on their variants.

enum Coin {
    Penny,  
    Nickel,  
    Dime,  
    Quarter,  
}

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,  
        Coin::Nickel => 5,  
        Coin::Dime => 10,  
        Coin::Quarter => 25,  
    }
}

The value_in_cents function takes an enum of type Coin and returns the corresponding value based on the name of the coins using the match syntax.

For Option, we also use match to handle the cases of None and Some, as well as perform basic operations that Some holds, as shown in the example in the beginning of the article.

fn plus_one(x: Option<i32>) -> Option<i32> {
    match x {
        None => None,  
        Some(i) => Some(i + 1),  
    }
}

let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);

The plus_one function takes an Option<i32> and adds 1 to its value. By matching the pattern, the function returns None if x is None, and if x is of type Some, meaning it contains a value, it returns a new Some value by adding 1 to the original value.

To help illustrate, match is similar to the switch...case statement in JavaScript. However, Rust provides a "Placeholder" or "catch-all" case, which captures any value that doesn't match the preceding cases.

let dice_roll = 9;
match dice_roll {
    3 => add_fancy_hat(),  
    7 => remove_fancy_hat(),  
    other => move_player(other),  
}

fn add_fancy_hat() {}
fn remove_fancy_hat() {}
fn move_player(num_spaces: u8) {}

Returning to the case of Option, sometimes we don't care much about None and only want to interact with the data if it exists in Some. In the following example, we always have to declare a placeholder to simply do nothing.

let config_max = Some(3u8);
match config_max {
    Some(max) => println!("The maximum is configured to be {}", max),  
    _ => (),  
}

This repetition can be tedious and unnecessary. Rust suggests using a combination of if let to specifically handle a certain case of an enum.

let config_max = Some(3u8);
if let Some(max) = config_max {
    println!("The maximum is configured to be {}", max);
}

Lastly, there is an important note about ownership when matching on Some which holds reference values. You can read more about it in The Rust Programming Language - How Matches Interact with Ownership.

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.
Author

Hello, my name is Hoai - a developer who tells stories through writing ✍️ and creating products 🚀. With many years of programming experience, I have contributed to various products that bring value to users at my workplace as well as to myself. My hobbies include reading, writing, and researching... I created this blog with the mission of delivering quality articles to the readers of 2coffee.dev.Follow me through these channels LinkedIn, Facebook, Instagram, Telegram.

Did you find this article helpful?
NoYes

Comments (1)

Avatar
Ẩn danh11 months ago
Mình cũng bắt đầu tìm hiểu về rust, bạn có muốn lập nhóm ngồi cf trao đổi để học không?
Reply
Avatar
Xuân Hoài Tống11 months ago
Chào bạn, rất vui khi nhận được lời đề nghị của bạn. Mình viết ra series tự học Rust để tạo cam kết cũng như ghi chép lại những gì học được, qua đó tóm tắt lại một cách cô đọng cho người đọc tham khảo. Tuy nhiên thì mình có nhiều lý do để rất khó lập được nhóm và cùng nhau trao đổi, như công việc và gia đình. Nhưng không sao, mình vẫn có thời gian cuối ngày để viết blog cũng như rất sẵn sàng trao đổi với bạn (dù không được realtime cho lắm). Hoặc nếu bạn cũng viết blog thì có thể để lại địa chỉ để cùng nhau học hỏi thêm :D