Defining and Utilizing Associated Constants in Rust
Associated constants in Rust provide a way to define constants that are associated with a type rather than a specific instance of that type. This is useful for representing values that are logically related to a type, such as default values, maximum sizes, or other type-specific metadata. This challenge will guide you through defining and using associated constants effectively.
Problem Description
You are tasked with creating a module named Geometry that defines a struct Rectangle with fields width and height, both of type u32. Within the Geometry module, you must define an associated constant named DEFAULT_WIDTH with a value of 10 and an associated constant named MAX_HEIGHT with a value of 50. Finally, create a function create_rectangle within the Geometry module that takes no arguments and returns a Rectangle initialized with DEFAULT_WIDTH for the width and MAX_HEIGHT for the height.
Key Requirements:
- Define the
Geometrymodule. - Define the
Rectanglestruct within theGeometrymodule. - Define
DEFAULT_WIDTHandMAX_HEIGHTas associated constants within theGeometrymodule. - Create the
create_rectanglefunction within theGeometrymodule. - The
create_rectanglefunction should return aRectangleinstance using the associated constants.
Expected Behavior:
The create_rectangle function should return a Rectangle with width equal to 10 and height equal to 50. The associated constants should be accessible through the Geometry module.
Edge Cases to Consider:
- Ensure the associated constants are correctly scoped within the
Geometrymodule. - Verify that the
create_rectanglefunction correctly utilizes the associated constants during initialization. - Consider that associated constants are
staticand immutable.
Examples
Example 1:
Input: None (function takes no arguments)
Output: Rectangle { width: 10, height: 50 }
Explanation: The `create_rectangle` function uses `Geometry::DEFAULT_WIDTH` and `Geometry::MAX_HEIGHT` to initialize a new `Rectangle` instance.
Constraints
- The
widthandheightfields of theRectanglestruct must be of typeu32. DEFAULT_WIDTHmust be 10.MAX_HEIGHTmust be 50.- The solution must be written in Rust.
- The code should be well-formatted and readable.
Notes
- Associated constants are declared using
constwithin a module. - They are accessible using the module name followed by the constant name (e.g.,
Geometry::DEFAULT_WIDTH). - Consider the immutability of associated constants when designing your solution. They cannot be changed after definition.
- Think about how associated constants improve code organization and readability compared to global constants.