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
Pointwith twoi32fields:xandy. - Implement the
std::fmt::Debugtrait for thePointstruct. - The debug output for
Point(x, y)should be formatted asPoint { x: <value_of_x>, y: <value_of_y> }. - Write a
mainfunction that creates an instance ofPointand 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
Pointstruct must have exactly two fields:xandy. - Both
xandyfields must be of typei32. - 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 yourfmtimplementation 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.