0
0
Rustprogramming~30 mins

Generic enums in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Generic Enums in Rust
📖 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.