pub trait DisplayPretty {
type Options: ?Sized;
// Required method
fn fmt(&self, f: &mut Formatter<'_>, options: &Self::Options) -> Result;
// Provided method
fn display<'a>(
&'a self,
options: &'a Self::Options,
) -> PrettyDisplay<'a, Self> { ... }
}Expand description
A trait for formatting values in a human-friendly, readable representation.
DisplayPretty is used when you want to maximize readability with indentation,
whitespace, and multi-line output. This is ideal for debugging, documentation,
or when human comprehension is more important than space efficiency.
§Use Cases
- Debugging: Easily readable output for complex data structures
- Pretty-printing ASTs: Multi-line formatted abstract syntax trees
- Configuration files: Human-editable output formats
- Error messages: Clear, well-formatted diagnostic information
§Options Type
The associated Options type typically carries indentation information.
Common patterns include:
usize: Current indentation level- Custom struct: With indent size, style preferences, etc.
§Examples
§Simple Pretty Display
use tokora::utils::DisplayPretty;
struct Point { x: i32, y: i32 }
impl DisplayPretty for Point {
type Options = ();
fn fmt(&self, f: &mut core::fmt::Formatter<'_>, _: &()) -> core::fmt::Result {
writeln!(f, "Point {{")?;
writeln!(f, " x: {},", self.x)?;
writeln!(f, " y: {}", self.y)?;
write!(f, "}}")
}
}
let p = Point { x: 10, y: 20 };
println!("{}", p.display(&()));
// Output:
// Point {
// x: 10,
// y: 20
// }§With Indentation
use tokora::utils::DisplayPretty;
struct Tree {
value: i32,
children: Vec<Tree>,
}
impl DisplayPretty for Tree {
type Options = usize; // indentation level
fn fmt(&self, f: &mut core::fmt::Formatter<'_>, indent: &usize) -> core::fmt::Result {
let spaces = " ".repeat(*indent);
writeln!(f, "{}Tree {{", spaces)?;
writeln!(f, "{} value: {}", spaces, self.value)?;
if !self.children.is_empty() {
writeln!(f, "{} children: [", spaces)?;
for child in &self.children {
child.fmt(f, &(indent + 2))?;
}
writeln!(f, "{} ]", spaces)?;
}
write!(f, "{}}}", spaces)
}
}
let tree = Tree {
value: 1,
children: vec![
Tree { value: 2, children: vec![] },
Tree { value: 3, children: vec![] },
],
};
println!("{}", tree.display(&0));Required Associated Types§
Required Methods§
Provided Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".