w3resource

Rust Program: Enum Direction

Rust Structs and Enums: Exercise-2 with Solution

Write a Rust program that creates an enum Direction with variants representing different directions (e.g., North, South, East, West).

Sample Solution:

Rust Code:

// Derive the Debug trait for the Direction enum
#[derive(Debug)]
// Define an enum named 'Direction' with variants representing different directions
enum Direction {
    North,
    South,
    East,
    West,
}

fn main() {
    // Example usage: Create variables representing different directions
    let north = Direction::North;
    let south = Direction::South;
    let east = Direction::East;
    let west = Direction::West;

    // Print the values of the variables representing directions
    println!("North: {:?}", north);
    println!("South: {:?}", south);
    println!("East: {:?}", east);
    println!("West: {:?}", west);
}

Output:

North: North
South: South
East: East
West: West

Explanation:

Here is a brief explanation of the above Rust code:

  • #[derive(Debug)]: This is a Rust attribute macro used to automatically implement the "Debug" trait for the "Direction" enum. The Debug trait allows types to be printed with debugging information using println!("{:?}", value).
  • enum Direction { ... }: Defines an enum named "Direction" with four variants: 'North', 'South', 'East', and 'West'. Enums in Rust allow you to define a type by enumerating its possible values.
  • fn main() { ... }: This is the main function, the entry point of the program.
  • Inside main():
    • Four variables ('north', 'south', 'east', and 'west') are created, each representing one of the directions defined in the "Direction" enum.
    • println!("{:?}", value) is used to print the values of the variables representing different directions. The {:?} format specifier is used to print the enum variants with debugging information, which is made possible by deriving the "Debug" trait for the "Direction" enum.

Rust Code Editor:

Previous: Rust Program: Rectangle area calculation.
Next: Rust Program: Calculate distance between Points.

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.