Hone logo
Hone
Problems

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 Point struct with x and y fields of type i32.
  • Implement the Display trait for the Point struct.
  • The Display implementation should return a string in the format "(x, y)".

Key requirements:

  • The implementation must adhere to the Display trait's contract.
  • The output string must be correctly formatted, including the parentheses and comma.
  • The x and y values 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 x and y.
  • Zero values for x and y.

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 Point struct fields must be of type i32.
  • 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::Display trait.
  • 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 Display trait requires you to implement the fmt method, which takes a reference to a Formatter and writes the formatted output to it. However, for this simple case, using format! is perfectly acceptable and more concise.
Loading editor...
rust