Hone logo
Hone
Problems

Implementing the Debug Trait in Rust

Debugging is a crucial part of software development. Rust provides the Debug trait, which allows types to be formatted for developer-facing output, typically used for debugging purposes. This challenge will test your understanding of how to implement and use the Debug trait for custom data structures.

Problem Description

Your task is to implement the std::fmt::Debug trait for a custom struct in Rust. This will enable you to print instances of your struct in a human-readable format using the {:?} format specifier. You will need to define how each field of your struct should be represented in the debug output.

Requirements:

  • Create a struct named Point with two i32 fields: x and y.
  • Implement the std::fmt::Debug trait for the Point struct.
  • The debug output for Point(x, y) should be formatted as Point { x: <value_of_x>, y: <value_of_y> }.
  • Write a main function that creates an instance of Point and prints it using the {:?} format specifier.

Expected Behavior:

When an instance of your Point struct is printed using println!("{:?}", my_point);, the output should clearly display the struct name and the values of its fields in the specified format.

Examples

Example 1:

Input:
let p = Point { x: 10, y: 20 };
println!("{:?}", p);
Output:
Point { x: 10, y: 20 }

Explanation: The Debug implementation formats the Point struct, showing its name and the values of its x and y fields.

Example 2:

Input:
let origin = Point { x: 0, y: 0 };
println!("{:?}", origin);
Output:
Point { x: 0, y: 0 }

Explanation: Demonstrates the same formatting for a different Point instance.

Constraints

  • The Point struct must have exactly two fields: x and y.
  • Both x and y fields must be of type i32.
  • The debug output format must strictly adhere to Point { x: <value_of_x>, y: <value_of_y> }.

Notes

  • You can use the write! macro within your fmt implementation to format and write the output.
  • Consider how you would delegate formatting to the debug implementations of the field types themselves.
  • The #[derive(Debug)] attribute automatically implements this trait, but for this challenge, you must implement it manually to understand the underlying mechanism.
Loading editor...
rust