w3resource

Rust Enum: Define Colors

Rust Basic: Exercise-16 with Solution

Write a Rust program that defines an enum Color with variants representing different colors.

Sample Solution:

Rust Code:

// Define an enum named 'Color' representing different colors
#[derive(Debug)] // Add #[derive(Debug)] to automatically implement the Debug trait
enum Color {
    // Variant representing the color Red
    Red,
    // Variant representing the color Green
    Green,
    // Variant representing the color Blue
    Blue,
}

fn main() {
    // Create variables of type 'Color' using the enum variants
    let red = Color::Red;
    let green = Color::Green;
    let blue = Color::Blue;

    // Print the values of the color variables
    println!("Red: {:?}", red);
    println!("Green: {:?}", green);
    println!("Blue: {:?}", blue);
}

Output:

Red: Red
Green: Green
Blue: Blue

Explanation:

Here's a brief explanation of the above Rust code:

  • #[derive(Debug)]: This attribute is used above the enum Color { ... } definition. It automatically implements the "Debug" trait for the "Color" enum, which allows instances of the enum to be printed using the println! macro with the {:?} format specifier.
  • enum Color { ... }: This line defines an enum named "Color" with three variants: 'Red', 'Green', and 'Blue'. Each variant represents a different color.
  • let red = Color::Red;, let green = Color::Green;, let blue = Color::Blue;: These lines create variables 'red', 'green', and 'blue', each of type "Color", and initialize them with one of the enum variants ('Red', 'Green', or 'Blue').
  • println!("Red: {:?}", red);, println!("Green: {:?}", green);, println!("Blue: {:?}", blue);: These lines print the values of the color variables using the println! macro. The {:?} format specifier is used to print the values using the "Debug" formatting, which was automatically implemented for the "Color" enum.

Rust Code Editor:

Previous: Rust Program: Print Person fields.
Next: Rust Function: Print optional integer.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.