Skip to content

Implementing and deriving traits using macros

Course: Rust for Solana contracts - chapter 22

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.

  1. 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);
  1. 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.
println("{}", v);

Deriving Debug / Display on your own struct

Section titled “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

impl std::fmt::Display for Rect {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.width, self.height)
}
}
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

Section titled “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);
}

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.

💡

This is one of the reasons why Debug has a default implementation for structs/hashmaps using macros but Display doesnt since display needs human intervention for a user friendly message