Lesson 12-Enum

1 분 소요

한국어(Korean) Page

Enums in Rust

Enums in Rust are similar to enums in other languages, but with added flexibility. They can be extended with impl blocks like structs and are commonly used for nullable variable declarations, making them highly versatile.

Let’s explore their functionality through examples.

enum Language {
  KOREAN,
  ENGLISH
}

fn main() {
  let default_lang = Language::KOREAN;
}

Struct-like Enum Variants

Enums can encapsulate data similar to structs:

enum Language {
    KOREAN(String),
    ENGLISH(String)
}

fn main() {
  let default_lang = Language::KOREAN(String::from("Korea"));
}

Tuple-like Enum Variants

Enums can also hold tuple-like data:

enum Language {
    KOREAN(String, i32),
    ENGLISH(String, i32)
}

fn main() {
  let default_lang = Language::KOREAN(String::from("Korea"), 82);
}

Complex Data Structures within Enums

Enums can accommodate various data models:

enum Book {
  UNKNOWN,
  WRITE { country: String, code: u32 },
  READ (String),
  PICTURE (i32)
  
}

Implementing Methods with impl

Enums can have methods defined using impl:

impl Book {
  fn Buy(&self) {
  
  }
}

Option Type

The Option type is used for declaring variables that can have a null value. It’s an enum with two variants: Some(T) for a value present and None for a null value.

enum Option<T> {
    Some(T),
    None,
}

let x: Option<i8> = Some(10);
let y = None;

Like nullable variables in other languages, Option variables cannot be directly used in operations with non-Option variables.

This leads to a compilation error, as demonstrated below.

fn main() {
  let x = 10;
  let y = Some(10);
  let sum = x + y;
}

//Result
  |
4 | let sum = x + y;
  |                    ^ no implementation for `i8 + std::option::Option<i8>`
  |
   = help: the trait `std::ops::Add<std::option::Option<i8>>` is not implemented for `i8`

댓글남기기