```rust use chain_debug::DebugExt;
struct A { inner: B, }
struct B { s: String, }
impl A { fn inner(&self) -> &B { &self.inner } }
let a = A { ... };
a .inner() .debug() .s .debug() ```
Sometime I will write some code like:
rust
let client = reqwest::Client::new();
let res = client
.post("example...")
.json(&payload)
.send()
.await
.unwrap()
.json::<Response>()
.await
.unwrap();
And there might be some error during query, then the final json parser will get unexpected JSON response that I need figure it out. But it is annoying to rewrite the code and break the chain calling for debugging.
rust
let response = client.post(...).response();
println!("{response:?}")
What if we can...
rust
// ...
.send()
.debug()
.json()
.debug()
We can inherit std::fmt::Debug
trait and extend it:
```rust pub trait DebugExt { fn debug(&self) -> &Self where Self: Debug, { println!("{self:?}"); self } }
impl
Then every struct that implied Debug
can automatically be implied DebugExt
,
thus we can inject .debug()
to inspect the value in the chain calling
without breaking the existing code.
Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=d283e02ea1b1041e04b21fc478f10271
Thanks for @SpriteOvO for teaching me about the trait inherit part.