Rust Enums Quiz

Rust
0 Passed
0% acceptance

40 comprehensive questions on Rust's enum system, covering simple variants, data-carrying variants, enum matching, methods on enums, and Option/Result patterns — with 11 code examples demonstrating practical enum usage.

40 Questions
~80 minutes
1

Question 1

What is an enum in Rust and why are they useful?

A
A type that can represent one of several possible variants, providing compile-time guarantees that all cases are handled
B
A way to create arrays with different types
C
A replacement for if-else statements
D
A way to define constants
2

Question 2

How do you define a simple enum with unit variants in Rust?

A
enum Name { Variant1, Variant2, Variant3 }
B
enum Name(Variant1, Variant2, Variant3)
C
enum Name { Variant1(), Variant2(), Variant3() }
D
enum Name = { Variant1, Variant2, Variant3 }
3

Question 3

What are data-carrying variants in enums?

A
Enum variants that can hold associated data of different types
B
Variants that carry metadata about the enum
C
Variants that automatically implement traits
D
Variants that can be converted to other types
4

Question 4

How do you define an enum variant that carries a single value?

A
VariantName(Type)
B
VariantName { value: Type }
C
VariantName = Type
D
VariantName(Type value)
5

Question 5

What will this enum definition create?

rust
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}
A
An enum with four variants: unit, struct-like, tuple-like, and tuple-like variants
B
An enum with only unit variants
C
An enum with only data-carrying variants
D
Compilation error - mixed variant types not allowed
6

Question 6

How do you create instances of enum variants?

A
EnumName::VariantName for unit variants, EnumName::VariantName(data) for data-carrying variants
B
VariantName for all variants
C
new EnumName(VariantName)
D
EnumName.VariantName
7

Question 7

What is the key benefit of using enums over constants or integers for representing different states?

A
Type safety and exhaustiveness checking ensure all possible states are handled
B
Enums use less memory
C
Enums are faster to compare
D
Enums can be easily serialized
8

Question 8

How do you implement methods on enums?

A
Use impl EnumName { fn method_name(&self) { ... } }
B
Use enum EnumName { ... fn method_name(&self) { ... } }
C
Methods cannot be implemented on enums
D
Use trait implementations only
9

Question 9

What will this enum method implementation do?

rust
enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter,
}

impl Coin {
    fn value_in_cents(&self) -> u32 {
        match self {
            Coin::Penny => 1,
            Coin::Nickel => 5,
            Coin::Dime => 10,
            Coin::Quarter => 25,
        }
    }
}
A
Adds a method to return the monetary value of each coin variant
B
Creates static methods for each variant
C
Compilation error - enums cannot have methods
D
Adds associated constants to the enum
10

Question 10

What is the Option enum and why is it commonly used?

A
An enum representing optional values with Some(T) and None variants, used to handle potentially missing data safely
B
An enum for boolean options
C
An enum for configuration options
D
An enum for command-line arguments
11

Question 11

How is the Option enum defined in Rust's standard library?

A
enum Option<T> { Some(T), None }
B
enum Option<T> { Some(T), Null }
C
enum Option<T> { Value(T), Empty }
D
Option is built into the language, not an enum
12

Question 12

What is the Result enum used for?

A
Representing operation outcomes with Ok(T) for success and Err(E) for errors
B
Representing mathematical results
C
Representing boolean results
D
Representing search results
13

Question 13

How do you handle Option values in practice?

A
Use match or if let to handle Some and None cases safely
B
Use .unwrap() to get the value directly
C
Check if the value is null
D
Use try-catch blocks
14

Question 14

What will this Option handling code output?

rust
fn main() {
    let some_number = Some(42);
    let absent_number: Option<i32> = None;
    
    match some_number {
        Some(value) => println!("Got a value: {}", value),
        None => println!("No value"),
    }
    
    match absent_number {
        Some(value) => println!("Got a value: {}", value),
        None => println!("No value"),
    }
}
A
Got a value: 42, No value
B
Got a value: 42, Got a value: 0
C
Compilation error
D
Runtime panic
15

Question 15

How do you use if let for concise Option handling?

A
if let Some(value) = option { ... } to execute code only when the option contains a value
B
if option.is_some() { ... }
C
if option != None { ... }
D
if let is not used with Option
16

Question 16

What is the ? operator used for with Result?

A
Propagating errors early by returning Err from the current function if a Result is Err
B
Unwrapping Results unsafely
C
Converting Results to Options
D
Creating Result values
17

Question 17

In a scenario where you're implementing a function that might fail, how should you design its return type?

A
Use Result<T, ErrorType> to indicate success or failure with specific error information
B
Use Option<T> for all error cases
C
Return T and panic on errors
D
Use exceptions like other languages
18

Question 18

How do you implement the Display trait for an enum?

A
Use impl Display for EnumName and implement fmt method with match on variants
B
Enums automatically implement Display
C
Use #[derive(Display)]
D
Display cannot be implemented for enums
19

Question 19

What is enum variant visibility and how does it work?

A
Enum variants are public if the enum is public, but can be restricted with pub(crate) or private modules
B
Variants have independent visibility from the enum
C
All variants are always public
D
Variants cannot be made private
20

Question 20

How do you create associated functions (static methods) on enums?

A
Use impl EnumName { fn new() -> Self { ... } } without &self parameter
B
Use static fn in the enum definition
C
Associated functions cannot be created on enums
D
Use class methods syntax
21

Question 21

What will this associated function on an enum create?

rust
enum Color {
    Red,
    Green,
    Blue,
}

impl Color {
    fn from_rgb(r: u8, g: u8, b: u8) -> Option<Self> {
        match (r, g, b) {
            (255, 0, 0) => Some(Color::Red),
            (0, 255, 0) => Some(Color::Green),
            (0, 0, 255) => Some(Color::Blue),
            _ => None,
        }
    }
}
A
A constructor function that creates Color variants from RGB values, returning None for invalid combinations
B
An instance method that converts colors to RGB
C
A method that validates RGB values
D
Compilation error - enums cannot have constructors
22

Question 22

How do you handle Result values in a match expression?

A
Match on Ok(value) for success and Err(error) for failure cases
B
Use if let Ok(value) = result for success handling
C
Both A and B are correct approaches
D
Result values cannot be matched
23

Question 23

What is the difference between Option and Result enums?

A
Option represents optional values (Some/None), Result represents operation outcomes (Ok/Err with error details)
B
Option is for errors, Result is for optional values
C
They are identical
D
Option has more variants than Result
24

Question 24

How do you chain operations that return Result using the ? operator?

A
fn process() -> Result<T, E> { let x = operation1()?; let y = operation2(x)?; Ok(y) }
B
Use try! macro instead of ?
C
The ? operator cannot be chained
D
Use match for each operation separately
25

Question 25

In a scenario where you're parsing user input that might be invalid, how should you structure the parsing function?

A
fn parse_input(s: &str) -> Result<ParsedData, ParseError> with specific error types for different failure modes
B
fn parse_input(s: &str) -> Option<ParsedData> for all error cases
C
fn parse_input(s: &str) -> ParsedData and panic on invalid input
D
Use exceptions for parsing errors
26

Question 26

What is enum discriminant and how does it work?

A
An integer value automatically assigned to each variant, starting from 0, used for memory representation
B
A string identifier for each variant
C
The data type associated with each variant
D
The visibility modifier for each variant
27

Question 27

How do you customize enum discriminants?

A
Use #[repr(u8)] or similar on the enum and assign values like Variant = 1
B
Discriminants cannot be customized
C
Use discriminant = value in the variant definition
D
Use const values for discriminants
28

Question 28

What is the memory layout of enums in Rust?

A
A discriminant tag plus enough space for the largest variant's data
B
Separate memory for each variant
C
Dynamic memory allocation for each variant
D
Enums use the same memory as their variants
29

Question 29

How do you implement From or Into traits for enums?

A
Use impl From<OtherType> for EnumName to define conversions, often with match expressions
B
Enums automatically implement conversion traits
C
Use #[derive(From)]
D
Conversions are not possible for enums
30

Question 30

What will this enum conversion implementation do?

rust
enum Status {
    Active,
    Inactive,
}

impl From<bool> for Status {
    fn from(b: bool) -> Self {
        if b { Status::Active } else { Status::Inactive }
    }
}
A
Allows converting bool values to Status variants using .into() or From::from()
B
Allows converting Status to bool
C
Creates a new Status variant
D
Compilation error - invalid conversion
31

Question 31

How do you handle C-style enums with custom discriminants?

A
enum MyEnum { Variant1 = 1, Variant2 = 5, Variant3 = 10 } with #[repr(C)] or similar
B
Use const values for discriminants
C
Custom discriminants are not supported
D
Use separate constants
32

Question 32

What is the difference between tuple variants and struct variants in enums?

A
Tuple variants use (type1, type2), struct variants use { field1: type1, field2: type2 }
B
Tuple variants are unnamed, struct variants are named
C
Both A and B are correct
D
There is no functional difference
33

Question 33

How do you pattern match on struct variants?

A
Use EnumName::VariantName { field1, field2 } => expression to destructure named fields
B
Use EnumName::VariantName(field1, field2) for struct variants
C
Struct variants cannot be pattern matched
D
Use dot notation for field access
34

Question 34

What will this struct variant matching code do?

rust
enum Shape {
    Circle { radius: f64 },
    Rectangle { width: f64, height: f64 },
}

fn main() {
    let shape = Shape::Rectangle { width: 10.0, height: 20.0 };
    match shape {
        Shape::Circle { radius } => println!("Circle with radius {}", radius),
        Shape::Rectangle { width, height } => println!("Rectangle {}x{}", width, height),
    }
}
A
Print 'Rectangle 10x20'
B
Print 'Circle with radius 10'
C
Compilation error
D
Runtime error
35

Question 35

How do you implement Default trait for an enum?

A
Use impl Default for EnumName { fn default() -> Self { EnumName::SomeVariant } }
B
Use #[derive(Default)] if the first variant should be default
C
Both A and B are valid approaches
D
Default cannot be implemented for enums
36

Question 36

What is the advantage of using enums over inheritance hierarchies?

A
Enums provide exhaustiveness checking and cannot be extended at runtime, ensuring type safety
B
Enums use less memory
C
Enums are faster to create
D
Enums support dynamic dispatch
37

Question 37

How do you handle nested enums in pattern matching?

A
Use nested match expressions or combine patterns with destructuring
B
Flatten the enum structure first
C
Use separate functions for each level
D
Nested enums cannot be matched
38

Question 38

What will this nested enum matching demonstrate?

rust
enum Result {
    Ok(i32),
    Err(String),
}

fn main() {
    let result = Result::Ok(42);
    match result {
        Result::Ok(n) if n > 0 => println!("Positive number: {}", n),
        Result::Ok(n) => println!("Zero or negative: {}", n),
        Result::Err(msg) => println!("Error: {}", msg),
    }
}
A
Shows how guards work with enum variants to add conditional logic
B
Demonstrates nested enum matching
C
Shows error handling patterns
D
All of the above
39

Question 39

How do you create recursive enums (enums that contain themselves)?

A
Use Box<EnumName> for recursive variants to avoid infinite size
B
Use Rc<EnumName> for shared ownership
C
Recursive enums are not allowed
D
Use &EnumName references
40

Question 40

In a complex application where you need to represent different types of user interface events, how would you design the event enum?

A
enum UiEvent { Click { x: i32, y: i32 }, KeyPress(char), Resize { width: u32, height: u32 }, Close } with appropriate data for each event type
B
Use separate structs for each event type
C
Use a single struct with optional fields
D
Use inheritance with a base Event class

QUIZZES IN Rust