Rust

[Rust] Enums

llHoYall 2022. 8. 6. 16:43

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;