Implementing a Custom Display Trait for Enhanced String Representation
The Display trait in Rust is fundamental for converting values into human-readable strings. While Rust provides a default implementation for many types, you often need more control over how your custom types are represented as strings. This challenge asks you to create a custom Display trait implementation for a specific struct, allowing you to define precisely how its fields are formatted when converted to a string.
Problem Description
You are tasked with creating a Display trait implementation for a struct called Point. The Point struct has two fields: x and y, both of type i32. The desired string representation of a Point should be in the format "(x, y)", where x and y are the values of the respective fields.
What needs to be achieved:
- Define a
Pointstruct withxandyfields of typei32. - Implement the
Displaytrait for thePointstruct. - The
Displayimplementation should return a string in the format "(x, y)".
Key requirements:
- The implementation must adhere to the
Displaytrait's contract. - The output string must be correctly formatted, including the parentheses and comma.
- The
xandyvalues should be converted to strings within the implementation.
Expected behavior:
Given a Point instance, calling the display() method (or using the {} format specifier) should return a string representation in the specified format.
Edge cases to consider:
- Negative values for
xandy. - Zero values for
xandy.
Examples
Example 1:
Input: Point { x: 2, y: 3 }
Output: "(2, 3)"
Explanation: The x value is 2 and the y value is 3, so the formatted string is "(2, 3)".
Example 2:
Input: Point { x: -1, y: 0 }
Output: "(-1, 0)"
Explanation: The x value is -1 and the y value is 0, so the formatted string is "(-1, 0)".
Example 3:
Input: Point { x: 0, y: 0 }
Output: "(0, 0)"
Explanation: Both x and y are 0, resulting in the string "(0, 0)".
Constraints
- The
Pointstruct fields must be of typei32. - The output string must be exactly in the format "(x, y)".
- The solution must compile and run without errors.
Notes
- Remember to use the
std::fmt::Displaytrait. - You'll need to use the
format!macro or similar string formatting techniques to construct the output string. - Consider using the
to_string()method on integer types to convert them to strings. - The
Displaytrait requires you to implement thefmtmethod, which takes a reference to aFormatterand writes the formatted output to it. However, for this simple case, usingformat!is perfectly acceptable and more concise.