Hone logo
Hone
Problems

Defining and Using Custom Enums in Rust

Enums are a powerful feature in Rust that allow you to define a type that can be one of several different variants. This is incredibly useful for representing states, options, or any situation where a variable can hold different kinds of data. This challenge will guide you through creating and utilizing a custom enum to model different types of fruits.

Problem Description

You are tasked with defining a Rust enum called Fruit that represents different types of fruits. The Fruit enum should have the following variants: Apple, Banana, Orange, and Grape. Each variant should be unit-like (i.e., have no associated data). After defining the enum, you need to create a function describe_fruit that takes a Fruit enum as input and prints a descriptive string based on the variant.

Key Requirements:

  • Define the Fruit enum with the specified variants.
  • Create a function describe_fruit that accepts a Fruit enum.
  • The describe_fruit function should use a match statement to determine the fruit type and print a corresponding message.
  • The output should be clear and informative.

Expected Behavior:

When describe_fruit is called with a specific Fruit variant, it should print a message indicating the fruit type. For example, calling describe_fruit(Fruit::Apple) should print "This is an Apple!".

Edge Cases to Consider:

  • Ensure the match statement covers all possible variants of the Fruit enum. While this is a simple enum, it's good practice to always be exhaustive in your match statements.

Examples

Example 1:

Input: describe_fruit(Fruit::Apple)
Output: This is an Apple!
Explanation: The function receives the `Apple` variant and prints the corresponding message.

Example 2:

Input: describe_fruit(Fruit::Banana)
Output: This is a Banana!
Explanation: The function receives the `Banana` variant and prints the corresponding message.

Example 3:

Input: describe_fruit(Fruit::Grape)
Output: This is a Grape!
Explanation: The function receives the `Grape` variant and prints the corresponding message.

Constraints

  • The Fruit enum must be defined using the enum keyword.
  • The describe_fruit function must use a match statement to determine the fruit type.
  • The output string must be exactly as specified in the examples.
  • The code must compile and run without errors.

Notes

  • Rust's match statement is a powerful tool for pattern matching and handling different enum variants.
  • Consider the importance of exhaustiveness when using match statements with enums. The compiler can help you ensure you've handled all possible cases.
  • This exercise focuses on the basic definition and usage of enums. More complex enums can have associated data, which you can explore later.
Loading editor...
rust