Rust Program: Implement Enum for Geometric shapes
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics