Rust - 列舉



在 Rust 程式設計中,當我們需要從一系列可能的變體中選擇一個值時,我們使用列舉資料型別。列舉型別使用 enum 關鍵字宣告。以下是 enum 的語法:

enum enum_name {
   variant1,
   variant2,
   variant3
}

示例:使用列舉

此示例聲明瞭一個列舉 - GenderCategory,它具有 Male 和 Female 兩種變體。print! 宏顯示列舉的值。編譯器會丟擲一個錯誤 trait std::fmt::Debug is not implemented for GenderCategory#[derive(Debug)] 屬性用於抑制此錯誤。

// The `derive` attribute automatically creates the implementation
// required to make this `enum` printable with `fmt::Debug`.
#[derive(Debug)]
enum GenderCategory {
   Male,Female
}
fn main() {
   let male = GenderCategory::Male;
   let female = GenderCategory::Female;

   println!("{:?}",male);
   println!("{:?}",female);
}

輸出

Male
Female

結構體和列舉

以下示例定義了一個 Person 結構體。gender 欄位的型別為 GenderCategory(這是一個列舉),可以賦值為 MaleFemale

// The `derive` attribute automatically creates the 
implementation
// required to make this `enum` printable with 
`fmt::Debug`.

#[derive(Debug)]
enum GenderCategory {
   Male,Female
}

// The `derive` attribute automatically creates the implementation
// required to make this `struct` printable with `fmt::Debug`.
#[derive(Debug)]
struct Person {
   name:String,
   gender:GenderCategory
}

fn main() {
   let p1 = Person {
      name:String::from("Mohtashim"),
      gender:GenderCategory::Male
   };
   let p2 = Person {
      name:String::from("Amy"),
      gender:GenderCategory::Female
   };
   println!("{:?}",p1);
   println!("{:?}",p2);
}

此示例建立了 Person 型別的 p1p2 物件,併為這些物件的名稱和性別屬性進行了初始化。

輸出

Person { name: "Mohtashim", gender: Male }
Person { name: "Amy", gender: Female }

Option 列舉

Option 是 Rust 標準庫中預定義的列舉。此列舉有兩個值 - Some(data) 和 None。

語法

enum Option<T> {
   Some(T),      //used to return a value
   None          // used to return null, as Rust doesn't support 
   the null keyword
}

這裡,型別 T 代表任何型別的數值。

Rust 不支援 null 關鍵字。在 enum Option 中,None 值可由函式用來返回空值。如果有資料要返回,則函式可以返回 Some(data)

讓我們透過一個例子來理解:

程式定義了一個函式 is_even(),其返回型別為 Option。該函式驗證傳遞的值是否為偶數。如果輸入為偶數,則返回 true 值,否則函式返回 None

fn main() {
   let result = is_even(3);
   println!("{:?}",result);
   println!("{:?}",is_even(30));
}
fn is_even(no:i32)->Option<bool> {
   if no%2 == 0 {
      Some(true)
   } else {
      None
   }
}

輸出

None
Some(true)

匹配語句和列舉

match 語句可用於比較儲存在列舉中的值。以下示例定義了一個函式 print_size,它將 CarType 列舉作為引數。該函式將引數值與預定義的一組常量進行比較,並顯示相應的訊息。

enum CarType {
   Hatch,
   Sedan,
   SUV
}
fn print_size(car:CarType) {
   match car {
      CarType::Hatch => {
         println!("Small sized car");
      },
      CarType::Sedan => {
         println!("medium sized car");
      },
      CarType::SUV =>{
         println!("Large sized Sports Utility car");
      }
   }
}
fn main(){
   print_size(CarType::SUV);
   print_size(CarType::Hatch);
   print_size(CarType::Sedan);
}

輸出

Large sized Sports Utility car
Small sized car
medium sized car

帶有 Option 的匹配

返回 Option 型別的 is_even 函式示例也可以使用 match 語句實現,如下所示:

fn main() {
   match is_even(5) {
      Some(data) => {
         if data==true {
            println!("Even no");
         }
      },
      None => {
         println!("not even");
      }
   }
}
fn is_even(no:i32)->Option<bool> {
   if no%2 == 0 {
      Some(true)
   } else {
      None
   }
}

輸出

not even

匹配 & 帶有資料型別的列舉

可以為列舉的每個變體新增資料型別。在以下示例中,列舉的 Name 和 Usr_ID 變體分別為 String 和整數型別。以下示例顯示了使用帶有資料型別的列舉的 match 語句。

// The `derive` attribute automatically creates the implementation
// required to make this `enum` printable with `fmt::Debug`.
#[derive(Debug)]
enum GenderCategory {
   Name(String),Usr_ID(i32)
}
fn main() {
   let p1 = GenderCategory::Name(String::from("Mohtashim"));
   let p2 = GenderCategory::Usr_ID(100);
   println!("{:?}",p1);
   println!("{:?}",p2);

   match p1 {
      GenderCategory::Name(val)=> {
         println!("{}",val);
      }
      GenderCategory::Usr_ID(val)=> {
         println!("{}",val);
      }
   }
}

輸出

Name("Mohtashim")
Usr_ID(100)
Mohtashim
廣告