본문 바로가기
Rust

[Rust] Enums

by llHoYall 2022. 8. 6.

Enums allow us to define a type by enumerating its possible variant.

Define Enums

Enums are one of the ways to define custom data types.

enum Fruits {
    Apple,
    Banana,
    Cherry,
}

We use the enum keyword to define enums.

Values of Enums

We can create instances of enums like this.

let apple = Fruits::Apple;
let banana = Fruirs::Banana;

The enum variants are namespaced under its identifier, and we use a double colon to separate the two.

The two variables are the same type.

 

We can put data directly into each enum variant.

enum Pet {
    Dog(String),
    Cat(String),
}

let my_dog = Pet::Dog(String::from("happy"));

Enums with Methods

We can define methods using impl like as struct's case.

impl Pet {
    fn cry(&self) { }
}

let my_dog = Pet::Dog(String::from("happy"));
my_dog.cry();

Option

The Option is enum in the standard library that is common and useful.

The Option types encode the very common scenario in which a value could be something or it could be nothing.

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

Option<T> enum can encode the concept of a value being present or absent.

We can use Some and None directly without the Option:: prefix.

<T> means the Some variant of the Option enum can hold one piece of data of any type.

Each concrete type that gets used in place of T makes the overall Option<T> type a different type.

let some_number = Some(5);
let some_string = Some("a string");

let none_number: Option<i32> = None;

'Rust' 카테고리의 다른 글

[Tauri] Getting Started with SvelteKit  (3) 2022.11.24
[Rust] Trait  (0) 2022.08.08
[Rust] Struct  (0) 2022.08.04
[Rust] List with Vector  (0) 2022.08.02
[Rust] Function  (0) 2022.08.01

댓글