init - added fmt_debug tinkering

This commit is contained in:
Ed Guloien
2026-06-09 14:30:26 -04:00
commit 5800faa0da
5 changed files with 91 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
/target
Generated
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "playground"
version = "0.1.0"
+6
View File
@@ -0,0 +1,6 @@
[package]
name = "playground"
version = "0.1.0"
edition = "2024"
[dependencies]
+72
View File
@@ -0,0 +1,72 @@
use std::fmt::Debug;
fn report<T: Debug>(item: T) {
println!("{:?}", item);
}
#[derive(Debug)]
struct Point {
x: u8,
y: u8,
}
#[derive(Debug)]
enum Thing {
One,
Two,
}
struct CustomPoint {
x: u8,
y: u8
}
// the same as derive(Debug)
impl std::fmt::Debug for CustomPoint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CustomPoint").field("x", &self.x). field("y", &self.y).finish()
}
}
// need to use newtype wrapper so we can implement std::fmt::Debug
struct Matrix([[u8; 5]; 5]);
impl std::fmt::Debug for Matrix {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// f.debug_list().entries(self.0.iter()).finish() // respects {:#?}
// best for human readable
for row in &self.0 {
writeln!(f, "{:?}", row)?;
}
Ok(())
}
}
// same as newtype, but generic, we get a stampped version for each type passed in the call
#[derive(Debug)]
struct GenericNewType<T>(T);
pub fn test_report() {
// works fine out of the box
report("string literal");
report("String".to_string());
report(['a','r', 'r', 'a', 'y']);
report(vec!['v','e', 'c', 't', 'o', 'r']);
report(1);
report(0x34); // prints as 52
report((1,2));
// needs #[derive(Debug)] or impl std::fmt::Debug
report(Point{x:1, y:2}); // prints "Point { x: 1, y: 2 }"
println!("{:#?}", Point { x: 1, y: 2 }); // pretty prints the fields on newlines
report(CustomPoint{x:1, y:2}); // prints "CustomPoint { x: 1, y: 2 }"
report(Thing::One); // prints "One"
report(Matrix([[0;5];5]));
//println!("{:#?}", [[0;5];5]); // pretty prints each element on newlines; a bit excessive
//
report(GenericNewType(2));
}
+5
View File
@@ -0,0 +1,5 @@
mod fmt_debug;
fn main() {
fmt_debug::test_report();
}