One Month Learning Rust - Enums and Pattern Matching

One Month Learning Rust - Enums and Pattern Matching

Daily short news for you
  • openai/codex is the latest open-source project from OpenAI, following their announcement of the two newest models, o3 and o4 mini. It is said that both o3 and o4 mini are very suitable for being Agents, so they released Codex as a lightweight Agent that runs directly in the Terminal.

    Regarding its applicability, since it is an Agent, it can read/add/edit/delete the contents of your files. For example.

    codex "explain this codebase to me"

    Or integrate it into your CI/CD pipeline.

    - name: Update changelog via Codex run: | npm install -g @openai/codex export OPENAI_API_KEY="${{ secrets.OPENAI_KEY }}" codex -a auto-edit --quiet "update CHANGELOG for next release"

    Oh, I almost forgot, you need to use the OpenAI API 😆

    » Read more
  • Perhaps many people do not know that OpenAI has launched its own academy page to help users learn and fully harness the power of their language models.

    OpenAI Academy

    » Read more
  • Mornings have started with some sensational news: OpenAI wants to acquire Windsurf for $3 billion 😳

    » 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

The secret stack of Blog

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click 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