One Month Learning Rust - Enums and Pattern Matching

One Month Learning Rust - Enums and Pattern Matching

Daily short news for you
  • A library brings a lot of motion effects to your website: animejs.com

    Go check it out, scroll a bit and your eyes will be dazzled 😵‍💫

    » Read more
  • A repository that compiles a list of system prompts that have been "leaked" on the Internet. Very useful for anyone researching how to write system prompts. I must say they are quite meticulous 😅

    jujumilk3/leaked-system-prompts

    » Read more
  • For over a week now, I haven't posted anything, not because I have nothing to write about, but because I'm looking for ways to distribute more valuable content in this rapidly exploding AI era.

    As I shared earlier this year, the number of visitors to my blog is gradually declining. When I looked at the statistics, the number of users in the first six months of 2025 has dropped by 30% compared to the same period last year, and by 15% compared to the last six months of 2024. This indicates a reality that users are gradually leaving. What is the reason for this?

    I think the biggest reason is that user habits have changed. They primarily discover the blog through search engines, with Google being the largest. Almost half of the users return to the blog without going through the search step. This is a positive signal, but it's still not enough to increase the number of new users. Not to mention that now, Google has launched the AI Search Labs feature, which means AI displays summarized content when users search, further reducing the likelihood of users accessing the website. Interestingly, when Search Labs was introduced, English articles have taken over the rankings for the most accessed content.

    My articles are usually very long, sometimes reaching up to 2000 words. Writing such an article takes a lot of time. It's normal for many articles to go unread. I know and accept this because not everyone encounters the issues being discussed. For me, writing is a way to cultivate patience and thoughtfulness. Being able to help someone through my writing is a wonderful thing.

    Therefore, I am thinking of focusing on shorter and medium-length content to be able to write more. Long content will only be used when I want to write in detail or delve deeply into a particular topic. So, I am looking for ways to redesign the blog. Everyone, please stay tuned! 😄

    » Read more

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.

Premium
Hello

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

View all

Subscribe to receive new article notifications

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

Comments (1)

Leave a comment...
Avatar
Ẩn danh1 year 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ống1 year 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