w3resource

Rust Program: Implement Enum for Geometric shapes

Rust Structs and Enums: Exercise-4 with Solution

Write a Rust program that implements an enum Shape with variants representing different geometric shapes (e.g., Circle, Triangle, Square).

Sample Solution:

Rust Code:

// Derive the Debug trait for the Shape enum
#[derive(Debug)]
// Define an enum named 'Shape' with variants representing different geometric shapes
enum Shape {
    Circle,
    Triangle,
    Square,
}

fn main() {
    // Example usage: Create variables representing different shapes
    let circle = Shape::Circle;
    let triangle = Shape::Triangle;
    let square = Shape::Square;

    // Print the values of the variables representing shapes
    println!("Circle: {:?}", circle);
    println!("Triangle: {:?}", triangle);
    println!("Square: {:?}", square);
}

Output:

Circle: Circle
Triangle: Triangle
Square: Square

Explanation:

Here is a brief explanation of the above Rust code:

The code defines an enum named "Shape" with variants representing different geometric shapes: "Circle", "Triangle", and "Square". The "Debug" trait is automatically derived for the "Shape" enum, allowing debugging information.

  • In the main() function,
    • Variables 'circle', 'triangle', and 'square' are created, each representing one of the shapes defined in the "Shape" enum.
    • The println! macro is used to print the values of these variables, allowing us to see which shape each variable represents.

Rust Code Editor:

Previous: Rust Program: Calculate distance between Points.
Next: Rust Program: Define Student Struct & Print details.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-4.php