One Month Learning Rust - Enums and Pattern Matching

One Month Learning Rust - Enums and Pattern Matching

Daily short news for you
  • For a long time, I have been thinking about how to increase brand presence, as well as users for the blog. After much contemplation, it seems the only way is to share on social media or hope they seek it out, until...

    Wearing this shirt means no more worries about traffic jams, the more crowded it gets, the more fun it is because hundreds of eyes are watching 🤓

    (It really works, you know 🤭)

    » Read more
  • A cycle of developing many projects is quite interesting. Summarized in 3 steps: See something complex -> Simplify it -> Add features until it becomes complex again... -> Back to a new loop.

    Why is that? Let me give you 2 examples to illustrate.

    Markdown was created with the aim of producing a plain text format that is "easy to write, easy to read, and easy to convert into something like HTML." At that time, no one had the patience to sit and write while also adding formatting for how the text displayed on the web. Yet now, people are "stuffing" or creating variations based on markdown to add so many new formats that… they can’t even remember all the syntax.

    React is also an example. Since the time of PHP, there has been a desire to create something that clearly separates the user interface from the core logic processing of applications into two distinct parts for better readability and writing. The result is that UI/UX libraries have developed very robustly, providing excellent user interaction, while the application logic resides on a separate server. The duo of Front-end and Back-end emerged from this, with the indispensable REST API waiter. Yet now, React doesn’t look much different from PHP, leading to Vue, Svelte... all converging back to a single point.

    However, the loop is not bad; on the contrary, this loop is more about evolution than "regression." Sometimes, it creates something good from something old, and people rely on that goodness to continue the loop. In other words, it’s about distilling the essence little by little 😁

    » Read more
  • Alongside the official projects, I occasionally see "side" projects aimed at optimizing or improving the language in some aspects. For example, nature-lang/nature is a project focused on enhancing Go, introducing some changes to make using Go more user-friendly.

    Looking back, it resembles JavaScript quite a bit 😆

    » 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