Rust Interview Questions

35 Questions
Rust

Rust

Web DevelopmentIoT

Question 30

What are enums in Rust, and how do you use them?

Answer:

In Rust, enums (short for "enumerations") are a powerful feature that allows you to define a type by enumerating its possible variants. Each variant of an enum can have associated data of different types. Enums are particularly useful for representing a value that could be one of several different states.

Defining Enums

Enums are defined using the enum keyword, followed by the name of the enum and a list of its variants.

Example: Basic Enum

enum Direction {
    North,
    South,
    East,
    West,
}

In this example, Direction is an enum with four variants: North, South, East, and West.

Using Enums

You can create instances of an enum by specifying the enum name followed by the variant name.

Example: Creating Enum Instances

fn main() {
    let direction = Direction::North;
}

Enum Variants with Data

Enum variants can also hold data. Each variant can have different types and amounts of associated data.

Example: Enum with Associated Data

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

In this example, Message is an enum with four variants:

  • Quit: No associated data.
  • Move: Contains two i32 values.
  • Write: Contains a String.
  • ChangeColor: Contains three i32 values.

Pattern Matching with Enums

Pattern matching is commonly used with enums to handle the different variants and their associated data.

Example: Pattern Matching

fn process_message(msg: Message) {
    match msg {
        Message::Quit => {
            println!("Quit");
        }
        Message::Move { x, y } => {
            println!("Move to ({}, {})", x, y);
        }
        Message::Write(text) => {
            println!("Write message: {}", text);
        }
        Message::ChangeColor(r, g, b) => {
            println!("Change color to red {}, green {}, blue {}", r, g, b);
        }
    }
}

fn main() {
    let msg1 = Message::Quit;
    let msg2 = Message::Move { x: 10, y: 20 };
    let msg3 = Message::Write(String::from("Hello"));
    let msg4 = Message::ChangeColor(255, 0, 0);

    process_message(msg1);
    process_message(msg2);
    process_message(msg3);
    process_message(msg4);
}

Using Enums with Option and Result

Rust's standard library includes two common enums: Option and Result.

Option Enum

The Option enum is used for values that may or may not be present.

fn main() {
    let some_number = Some(5);
    let no_number: Option<i32> = None;

    match some_number {
        Some(value) => println!("We have a value: {}", value),
        None => println!("No value"),
    }
}

Result Enum

The Result enum is used for error handling and represents either a success (Ok) or an error (Err).

fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err(String::from("Cannot divide by zero"))
    } else {
        Ok(a / b)
    }
}

fn main() {
    match divide(10, 2) {
        Ok(result) => println!("Result: {}", result),
        Err(error) => println!("Error: {}", error),
    }

    match divide(10, 0) {
        Ok(result) => println!("Result: {}", result),
        Err(error) => println!("Error: {}", error),
    }
}

Summary

  • Enums: Enums allow you to define a type with multiple variants, each of which can hold different types and amounts of data.
  • Defining Enums: Use the enum keyword followed by variant names.
  • Using Enums: Create instances of enum variants by specifying the enum name and variant name.
  • Pattern Matching: Use match expressions to handle different enum variants and their associated data.
  • Common Enums: Rustโ€™s standard library includes useful enums like Option and Result for handling optional values and errors.

Enums in Rust provide a flexible and powerful way to represent data that can be in one of several states, enabling you to write robust and expressive code.

Recent job openings