Hone logo
Hone
Problems

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 Circle should store its radius (a floating-point number, f32).
  • A Rectangle should store its width and height (both f32).
  • A Triangle should store the lengths of its three sides (a tuple of three f32 values).

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, and Triangle.
  • Associate the correct data types with each variant.
  • Implement a function describe_shape that accepts a Shape and returns a String.

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 f32 floating-point numbers.
  • The sides tuple for a Triangle will always contain exactly three f32 values.

Notes

  • You'll need to use pattern matching (match) within your describe_shape function 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 the describe_shape function itself.
Loading editor...
rust