One Month Learning Rust - Enums and Pattern Matching

One Month Learning Rust - Enums and Pattern Matching

Daily short news for you
  • Since the Lunar New Year holiday has started, I won't be posting anymore. See you all after the holiday! 😁

    » Read more
  • Continuing about jj. I'm wondering if there are any GUI software made for it yet to make it easier to use. There are already so many similar to git that I can't count them all.

    Luckily, the author has compiled them all together in Community-built tools around Jujutsu 🥳

    » Read more
  • Turso announces that they are rewriting SQLite in Rust. This adds another piece of evidence supporting the notion that Rust is "redefining" many things.

    But the deeper reason is more interesting. Why are they doing this? Everyone knows that SQLite is open source, and anyone can create a fork to modify it as they wish. Does the Turso team dislike or distrust C—the language used to build SQLite?

    Let me share a bit of a story. Turso is a provider of database server services based on SQLite; they have made some customizations to a fork of SQLite to serve their purposes, calling it libSQL. They are "generous" in allowing the community to contribute freely.

    Returning to the point that SQLite is open source but not open contribution. There is only a small group of people behind the maintenance of this source code, and they do not accept pull requests from others. This means that any changes or features are created solely by this group. It seems that SQLite is very popular, but the community cannot do what they want, which is to contribute to its development.

    We know that most open source applications usually come with a "tests" directory that contains very strict tests. This makes collaboration in development much easier. If you want to modify or add a new feature, you first need to ensure that the changes pass all the tests. Many reports suggest that SQLite does not publicly share this testing suite. This inadvertently makes it difficult for those who want to modify the source code, as they are uncertain whether their new implementation is compatible with the existing features.

    tursodatabase/limbo is the project rewriting SQLite in Rust mentioned at the beginning of this article. They claim that it is fully compatible with SQLite and completely open source. Limbo is currently in the final stages of development. Let’s wait and see what the results will be in the future. For a detailed article, visit Introducing Limbo: A complete rewrite of SQLite in Rust.

    » 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

5 profound lessons

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? 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
Scroll or click to go to the next page