Define a Rust Enum for Geometric Shapes
Enums in Rust are a powerful way to define a type that can be one of several possible variants. This challenge focuses on creating a simple enum to represent different geometric shapes, a common pattern in many programming applications, such as game development or graphics rendering.
Problem Description
Your task is to define a Rust enum named Shape that can represent three distinct geometric shapes: a Circle, a Rectangle, and a Triangle.
Each shape variant should carry specific data:
- A
Circleshould store itsradius(a floating-point number,f32). - A
Rectangleshould store itswidthandheight(bothf32). - A
Triangleshould store the lengths of its threesides(a tuple of threef32values).
You should also implement a simple function that takes a Shape and returns a string describing the shape and its dimensions.
Key Requirements:
- Create an enum named
Shape. - Define variants for
Circle,Rectangle, andTriangle. - Associate the correct data types with each variant.
- Implement a function
describe_shapethat accepts aShapeand returns aString.
Expected Behavior:
When describe_shape is called with different Shape variants, it should produce descriptive strings as shown in the examples.
Examples
Example 1:
let circle = Shape::Circle { radius: 5.0 };
let description = describe_shape(circle);
// description should be "Circle with radius 5.0"
Explanation: The input is a Circle with a radius of 5.0. The describe_shape function correctly identifies it as a circle and formats the output string.
Example 2:
let rectangle = Shape::Rectangle { width: 10.0, height: 4.0 };
let description = describe_shape(rectangle);
// description should be "Rectangle with width 10.0 and height 4.0"
Explanation: The input is a Rectangle with a width of 10.0 and a height of 4.0. The function formats the output string accordingly.
Example 3:
let triangle = Shape::Triangle { sides: (3.0, 4.0, 5.0) };
let description = describe_shape(triangle);
// description should be "Triangle with sides (3.0, 4.0, 5.0)"
Explanation: The input is a Triangle with side lengths 3.0, 4.0, and 5.0. The function represents the sides as a tuple in the output string.
Constraints
- All numerical values (radius, width, height, sides) will be non-negative
f32floating-point numbers. - The
sidestuple for aTrianglewill always contain exactly threef32values.
Notes
- You'll need to use pattern matching (
match) within yourdescribe_shapefunction to handle the different enum variants. - Consider how to format the floating-point numbers in the output string. The
format!macro will be very useful here. - Think about making your enum printable using
#[derive(Debug)]for easier debugging if needed, though it's not strictly required for thedescribe_shapefunction itself.