Code Logo

Derive Debug for Formatting

Published at25 Jul 2026
Rust Traits & Generics Easy 0 views
Like0

Write a Rust function that defines a Point struct with x and y fields, derives the Debug trait, and returns the Debug representation of a Point as a String using format!("{:?}", point). The Debug trait enables the {:?} format specifier used for debugging output.

The #[derive(Debug)] attribute is one of the most commonly used derive macros in Rust. It automatically generates an implementation of std::fmt::Debug for the struct, which produces output like "Point { x: 3, y: 4 }". This is invaluable for logging, error messages, and assert_eq! failure messages.

Unlike Display which must be manually implemented for each type, Debug can be derived automatically for any struct where all fields implement Debug. Most standard library types implement Debug, making it widely available. The compiler suggests adding #[derive(Debug)] when it encounters {:?} formatting for a type that doesn't implement Debug.

Time complexity is O(n) where n is the number of fields. Space complexity is O(k) for the formatted string. The derived implementation produces consistent, predictable output for debugging purposes.

Edge cases include structs with many fields, nested structs that also implement Debug, and ensuring the #[derive(Debug)] attribute is placed correctly above the struct definition.

Example Input & Output

Example 1
Input
(3,4)
Output
"Point(3, 4)"
Explanation

Debug format shows struct fields

Example 2
Input
(-1,5)
Output
"Point(-1, 5)"
Explanation

Negative x

Example 3
Input
(10,20)
Output
"Point(10, 20)"
Explanation

Positive values

Example 4
Input
(100,200)
Output
"Point(100, 200)"
Explanation

Large values

Example 5
Input
(0,0)
Output
"Point(0, 0)"
Explanation

Origin point

Algorithm Flow

Recommendation Algorithm Flow for Derive Debug for Formatting
Recommendation Algorithm Flow for Derive Debug for Formatting

Solution Approach

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn solution(x: i32, y: i32) -> String {
    let p = Point { x, y };
    format!("{:?}", p)
}

Best Answers

rust - Approach 1
#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn solution(x: i32, y: i32) -> String {
    let p = Point { x, y };
    format!("{:?}", p)
}