commit 5800faa0da43a87b313dbd36ef68bc8c2fae4b68 Author: Ed Guloien Date: Tue Jun 9 14:30:26 2026 -0400 init - added fmt_debug tinkering diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..ce90dbc --- /dev/null +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..c92d524 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "playground" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/src/fmt_debug.rs b/src/fmt_debug.rs new file mode 100644 index 0000000..5d5fafb --- /dev/null +++ b/src/fmt_debug.rs @@ -0,0 +1,72 @@ +use std::fmt::Debug; + +fn report(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); + + +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)); + +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..18a4de1 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,5 @@ +mod fmt_debug; + +fn main() { + fmt_debug::test_report(); +}