Enums

Like tuples, enums can also be destructured by matching:

الگوها همچنین می توانند برای انتساب متغیرها استفاده شوند.به این ترتیب ساختار انواع (Types) خود را بررسی می‌کنید. اجازه دهید با یک نوع enum ساده شروع کنیم:

enum Result {
    Ok(i32),
    Err(String),
}

fn divide_in_two(n: i32) -> Result {
    if n % 2 == 0 {
        Result::Ok(n / 2)
    } else {
        Result::Err(format!("cannot divide {n} into two equal parts"))
    }
}

fn main() {
    let n = 100;
    match divide_in_two(n) {
        Result::Ok(half) => println!("{n} divided in two is {half}"),
        Result::Err(msg) => println!("sorry, an error happened: {msg}"),
    }
}

در اینجا ما از شاخه‌ها برای destructure کردن مقدار Result استفاده کرده‌ایم. در شاخه اول، half به مقداری داخل نوع Ok متصل می شود. در شاخه دوم، msg به نوعErr متصل می‌شود.

This slide should take about 4 minutes.
  • عبارت if/else یک enum را برمی گرداند که بعداً با match باز می شود.
  • می توانید با اضافه کردن یک فیلد دیگر None به enum اضافه کنید و نمایش خطاها هنگام اجرای کد، را تست کنید. مکان هایی را که کد شما اکنون ناقص است و نحوه تلاش کامپایلر برای ارائه نکاتی به شما را نشان دهید.
  • The values in the enum variants can only be accessed after being pattern matched.
  • Demonstrate what happens when the search is inexhaustive. Note the advantage the Rust compiler provides by confirming when all cases are handled.
  • Save the result of divide_in_two in the result variable and match it in a loop. That won’t compile because msg is consumed when matched. To fix it, match &result instead of result. That will make msg a reference so it won’t be consumed. This “match ergonomics” appeared in Rust 2018. If you want to support older Rust, replace msg with ref msg in the pattern.