📖 Scenario: You are building a simple program to store different types of values using a generic enum in Rust. This helps you keep related data together in one place, like storing either a number or a text message.
🎯 Goal: Create a generic enum called Value that can hold either a number or a text. Then, create instances of this enum with different types and print their contents.
📋 What You'll Learn
Define a generic enum named Value with two variants: Number and Text.
Create a variable num_value of type Value<i32> holding the number 42.
Create a variable text_value of type Value<String> holding the text "Hello".
Use a match statement to print the contents of both variables.
💡 Why This Matters
🌍 Real World
Generic enums let you store different types of related data in one variable, useful in many programs like handling user input, configuration options, or messages.
💼 Career
Understanding generic enums is important for Rust developers to write flexible and reusable code, a common requirement in systems programming and software development.
Progress0 / 4 steps
1
Define the generic enum Value
Define a generic enum called Value with a type parameter T. It should have two variants: Number holding a value of type T, and Text holding a value of type T.
Rust
Hint
Use enum Value<T> and define variants with T as the type.
2
Create variables using the generic enum
Create a variable called num_value of type Value<i32> holding the number 42. Also create a variable called text_value of type Value<String> holding the text "Hello".
Rust
Hint
Use Value::Number(42) and Value::Text(String::from("Hello")) to create the variables.
3
Use match to access enum contents
Write a match statement to check the variant of num_value. If it is Number, print "Number: {value}". If it is Text, print "Text: {value}". Do the same for text_value.
Rust
Hint
Use match variable { Value::Number(val) => ..., Value::Text(val) => ... } to check variants.
4
Print the enum contents
Add println! statements inside the match arms to print the values of num_value and text_value exactly as shown: Number: 42 and Text: Hello.
Rust
Hint
Make sure the printed output matches exactly: Number: 42 and Text: Hello.
Practice
(1/5)
1. What is the main benefit of using generic enums in Rust?
easy
A. They allow enums to hold different types of data without rewriting code.
B. They make enums run faster by using less memory.
C. They automatically generate functions for enums.
D. They restrict enums to only one data type.
Solution
Step 1: Understand what generic enums do
Generic enums let you define an enum that can hold different types of data by using type parameters.
Step 2: Identify the benefit
This means you can reuse the same enum for many data types without rewriting it for each type.
Final Answer:
They allow enums to hold different types of data without rewriting code. -> Option A
Quick Check:
Generic enums = flexible data types [OK]
Hint: Generic enums = one enum, many data types [OK]
Common Mistakes:
Thinking generic enums improve speed
Believing they auto-generate functions
Assuming they limit data types
2. Which of the following is the correct syntax to define a generic enum named Option with a type parameter T?
easy
A. enum Option<T> { Some(T), None }
B. enum Option { Some<T>(T), None }
C. enum Option<T> { Some, None(T) }
D. enum Option { Some(T), None }
Solution
Step 1: Recall generic enum syntax
Generic enums declare the type parameter after the enum name, like enum Name<T>.
Step 2: Check variant definitions
Variants can use the generic type T directly, e.g., Some(T). The None variant has no data.
Final Answer:
enum Option<T> { Some(T), None } -> Option A
Quick Check:
Generic param after enum name = enum Option<T> { Some(T), None } [OK]
Hint: Generic param goes after enum name, not variant [OK]
Common Mistakes:
Putting <T> after variant name
Adding data to None variant
Omitting generic parameter after enum name
3. What will be the output of this Rust code?
enum Result {
Ok(T),
Err(E),
}
fn main() {
let value: Result = Result::Ok(10);
match value {
Result::Ok(v) => println!("Value: {}", v),
Result::Err(e) => println!("Error: {}", e),
}
}
medium
A. Compilation error
B. Error: 10
C. Value: Err
D. Value: 10
Solution
Step 1: Understand the enum and value
The enum Result has two variants: Ok with type T and Err with type E. The variable value is Result::Ok(10).
Step 2: Match arms and output
The match checks if value is Ok or Err. Since it is Ok(10), it prints Value: 10.
Final Answer:
Value: 10 -> Option D
Quick Check:
Match Ok(10) prints Value: 10 [OK]
Hint: Match enum variant to print correct value [OK]
Which code correctly creates a Container holding multiple String values and prints each string?
hard
A. let c: Container = Container::Multiple(vec!["a", "b"]);
match c {
Container::Multiple(v) => for s in v { println!("{}", s); },
_ => (),
}
B. let c = Container::Multiple(vec!["a".to_string(), "b".to_string()]);
if let Container::Multiple(v) = c {
for s in v { println!("{}", s); }
}
C. let c = Container::Single(vec!["a".to_string(), "b".to_string()]);
match c {
Container::Multiple(v) => for s in v { println!("{}", s); },
_ => (),
}
D. let c = Container::Multiple(vec!["a", "b"]);
if let Container::Multiple(v) = c {
for s in v { println!("{}", s); }
}
Solution
Step 1: Check type correctness in creation
The enum Container expects Vec<T> for Multiple. Using vec!["a".to_string(), "b".to_string()] creates a Vec<String>, matching Container<String>.
Step 2: Verify pattern matching and printing
The if let correctly matches Container::Multiple(v) and iterates over v to print each string.
Final Answer:
Code correctly creates and prints the strings. -> Option B
Quick Check:
Correct generic type and pattern matching = let c = Container::Multiple(vec!["a".to_string(), "b".to_string()]);
if let Container::Multiple(v) = c {
for s in v { println!("{}", s); }
} [OK]
Hint: Use to_string() for String vectors and match variants properly [OK]
Common Mistakes:
Missing generic type annotation
Using wrong variant for multiple values
Using string slices instead of String objects
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.