init - added fmt_debug tinkering
This commit is contained in:
@@ -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));
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
mod fmt_debug;
|
||||
|
||||
fn main() {
|
||||
fmt_debug::test_report();
|
||||
}
|
||||
Reference in New Issue
Block a user