Associated Constants for Geometric Shapes
In Rust, associated constants are values that are defined within an impl block for a trait or a struct. They are useful for providing named, unchanging values that are logically tied to a specific type or behavior. This challenge focuses on implementing associated constants within a trait to represent inherent properties of different geometric shapes.
Problem Description
Your task is to define a trait Shape that includes an associated constant SIDES. This constant should represent the number of sides for different geometric shapes. You will then implement this trait for several concrete shape types, such as Triangle, Square, and Hexagon, providing the correct number of sides for each.
Key Requirements:
- Define a trait named
Shape. - This trait must have an associated constant named
SIDESof typeusize. - Implement the
Shapetrait for the following structs:TriangleSquareHexagon
- For each implemented struct, the
SIDESassociated constant should correctly reflect the number of sides of that shape.
Expected Behavior:
When you access Triangle::SIDES, it should yield 3.
When you access Square::SIDES, it should yield 4.
When you access Hexagon::SIDES, it should yield 6.
Examples
Example 1:
struct Triangle;
struct Square;
struct Hexagon;
// ... trait and impl blocks ...
assert_eq!(Triangle::SIDES, 3);
Output:
3
Explanation: The Triangle struct correctly implements the Shape trait, and its associated SIDES constant is set to 3.
Example 2:
struct Triangle;
struct Square;
struct Hexagon;
// ... trait and impl blocks ...
assert_eq!(Square::SIDES, 4);
Output:
4
Explanation: The Square struct correctly implements the Shape trait, and its associated SIDES constant is set to 4.
Example 3:
struct Triangle;
struct Square;
struct Hexagon;
// ... trait and impl blocks ...
assert_eq!(Hexagon::SIDES, 6);
Output:
6
Explanation: The Hexagon struct correctly implements the Shape trait, and its associated SIDES constant is set to 6.
Constraints
- The associated constant
SIDESmust be of typeusize. - The structs
Triangle,Square, andHexagonshould be defined with no fields (they are unit structs). - The implementation must be in Rust.
Notes
- Associated constants are defined using the
constkeyword within animplblock. - You do not need to implement any methods for the
Shapetrait; only the associated constant is required. - This challenge helps solidify your understanding of how to define and implement associated constants, which are fundamental for defining shared properties across different types.