CodeBlanks Logo Icon CodeBlanks

Enum definition

Define enumerations with enum.

Defining an enum

An enum (enumeration) is a type expressing that a value can be exactly one of a fixed set of options. Each option is called a variant:

#[derive(Debug)]
enum Yon {
    Kuzey,
    Guney,
    Dogu,
    Bati,
}

let y = Yon::Dogu;
println!("{:?}", y);   // Dogu

Variants are qualified with the enum name: Yon::Dogu. A struct models an "and" relation (name and score), an enum models an "or" relation (north or south).

Enums and integers

Variants that carry no data are stored with a number (the discriminant) behind the scenes; it can be set explicitly and converted to an integer with as:

enum Durum {
    Bekliyor = 1,
    Hazir = 2,
    Hata = 9,
}

println!("{}", Durum::Hata as i32);   // 9

The reverse (integer to enum) isn't automatic; since invalid numbers are possible, it's written by hand with match.

Practice Direction enum

Define enum Yon with the variants Kuzey, Guney, Dogu and Bati, with #[derive(Debug)]. Assign Yon::Dogu to a variable and print it with {:?}.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
#[derive(Debug)]
enum Yon {
    Kuzey,
    Guney,
    Dogu,
    Bati,
}

fn main() {
    let y = Yon::Dogu;
    println!("{:?}", y);
}

Expected output

Dogu

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is the best fit for an enum?

  • A piece of text
  • A traffic light colour: red, yellow, green Correct answer
  • A person's name and age
  • A list of numbers

Explanation: If the value can only be one of fixed options, an enum is the natural choice.

2 Pick a variant

Question
let y = Yon____Bati;
Answer
let y = Yon::Bati;

Explanation: Variants are written as EnumName::Variant.

3 Concept and example

Term Meaning
enum Yon { .. } Enum definition
Yon::Dogu Variant value
Durum::Hata as i32 Discriminant
#[derive(Debug)] Prints the variant name

All lessons in Beginner