custom_debug/
custom_debug.rs

1use std::{fmt, marker::PhantomData};
2
3use fmt_ext::{debug::*, DebugExt};
4
5// Create a type that will implement custom debug...
6struct SliceWithLenDebug<T>(PhantomData<T>);
7
8// Implement custom debug...
9impl<T> CustomDebug for SliceWithLenDebug<T>
10where
11    T: fmt::Debug,
12{
13    type Target = [T];
14
15    fn fmt_target(target: &Self::Target, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16        write!(f, "Slice {{ len: {}, items: {:?} }}", target.len(), target)
17    }
18}
19
20// Attach custom debug implementation to the target type...
21impl<T> AttachDebug<SliceWithLenDebug<T>> for [T] {}
22
23// Look! We have just call `debug` method on the target type...
24fn main() {
25    let numbers = [0, 1, 2, 3];
26    println!("{:?}", numbers.debug());
27
28    let strings = vec!["I", "am", "a", "custom", "debug"];
29    println!("{:?}", strings.debug());
30}