Debug and Display trait and macros
Debug and Display trait
In Rust, the Debug
and Display
traits are part of the standard library, and they allow you to control how an object is printed or formatted as a string.
-
Debug:
- The
Debug
trait is used to provide a formatted representation of an object for debugging purposes. - It’s generally used with the
{:?}
syntax when printing or formatting objects.
println("{:?}", v); - The
-
Display:
- The
Display
trait is used to provide a user-friendly string representation of an object. - It’s used with the
{}
syntax when formatting or printing objects.
- The
println("{}", v);
Deriving Debug
/ Display
on your own struct
Lets say you have your own struct called Rect
struct Rect { width: u32, height: u32}
fn main() { let s = Rect { width: 100, height: 100 }; println!("{}", s);}
If you try printing a rectangle
, you will see the following error
Implementing the Display
trait manually
impl std::fmt::Display for Rect { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({}, {})", self.width, self.height) }}
Implementing the Debug
trait manually
use std::fmt;
struct Rect { width: u32, height: u32}
impl std::fmt::Debug for Rect { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({}, {})", self.width, self.height) }}
fn main() { let s = Rect { width: 100, height: 100 }; println!("{:?}", s);}
Deriving the Debug
trait using the Debug macro
use std::fmt;
#[derive(Debug)]struct Rect { width: u32, height: u32}
fn main() { let s = Rect { width: 100, height: 100 }; println!("{:?}", s);}
Difference between Debug
and Derive
The difference between the Debug
and Display
traits in Rust is rooted in their intended purpose and the way they represent data.
Debug
- Primarily intended for debugging and inspecting values in a developer-friendly format.
Display
- The Display
trait is intended for user-facing output, focusing on simplicity and readability. It’s used when you want to format an object in a way that’s easy to understand for end users.