Rust Program: Enum Colors
Rust Structs and Enums: Exercise-8 with Solution
Write a Rust program that implements an enum Color with variants representing different colors (e.g., Red, Green, Blue).
Sample Solution:
Rust Code:
// Define an enum named 'Color' with variants representing different colors
#[derive(Debug)]
enum Color {
Red,
Green,
Blue,
}
fn main() {
// Create variables representing different colors
let red = Color::Red;
let green = Color::Green;
let blue = Color::Blue;
// Print the values of the variables representing colors
println!("Red: {:?}", red);
println!("Green: {:?}", green);
println!("Blue: {:?}", blue);
}
Output:
Red: Red Green: Green Blue: Blue
Explanation:
The above Rust code defines an enum called 'Color', which represents different colors ('Red', 'Green', and 'Blue'). Inside the 'main' function, it creates variables for each color variant and prints out their values using the 'println!' macro with the '{:?}' format specifier, which is enabled by deriving the 'Debug' trait for the 'Color' enum. This allows the program to print the enum variants along with their associated data for debugging purposes.
Rust Code Editor:
Previous: Rust Program: Calculate employee annual salary.
Next: Rust Program: Car Details.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/rust/basic/rust-structs-and-enums-exercise-8.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics