Implementing a Debug Trait for Custom Data Structures in Rust
This challenge focuses on implementing the Debug trait for custom data structures in Rust. The Debug trait allows you to easily print the contents of your data structures for debugging purposes, making it an essential tool for any Rust developer. Your task is to implement this trait for a provided custom struct.
Problem Description
You are given a struct called Point representing a 2D point with x and y coordinates, both of type i32. Your goal is to implement the Debug trait for the Point struct. The implementation should provide a human-readable representation of the Point when printed using {:?} or {:#?} format specifiers.
Key Requirements:
- Implement the
Debugtrait for thePointstruct. - The
Debugimplementation should include both thefmtmethod. - The
fmtmethod should format the output in a clear and understandable way, including thexandycoordinates. - The
fmtmethod should handle different formatting styles (e.g., pretty printing with{:#?}).
Expected Behavior:
When a Point instance is printed using {:?}, the output should be in the format Point { x: <x_value>, y: <y_value> }. When printed using {:#?}, the output should be formatted with indentation for better readability, like:
Point {
x: <x_value>,
y: <y_value>,
}
Edge Cases to Consider:
- Negative coordinate values.
- Zero coordinate values.
- The formatting differences between
{:?}and{:#?}.
Examples
Example 1:
Input: Point { x: 10, y: 20 }
Output: Point { x: 10, y: 20 }
Explanation: A standard `{:?}` format.
Example 2:
Input: Point { x: -5, y: 0 }
Output: Point { x: -5, y: 0 }
Explanation: Handles negative and zero values correctly.
Example 3:
Input: Point { x: 10, y: 20 }
Output:
Point {
x: 10,
y: 20,
}
Explanation: `{:#?}` format with indentation.
Constraints
- The
Pointstruct will always containi32values forxandy. - The output format must strictly adhere to the specifications outlined in the "Expected Behavior" section.
- The solution must compile and run without errors.
Notes
- The
Debugtrait is part of thestd::fmtmodule. - The
fmtmethod takes a reference to aFormatterstruct, which provides methods for formatting the output. - Consider using the
write!macro to write the formatted output to theFormatter. - Pay close attention to the differences in formatting required by
{:?}and{:#?}. The latter requires indentation.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
impl std::fmt::Debug for Point {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Your code here
}
}
fn main() {
let p1 = Point { x: 10, y: 20 };
let p2 = Point { x: -5, y: 0 };
println!("{:?}", p1);
println!("{:?}", p2);
println!("{:#?}", p1);
}