Custom Debug Output With debug_struct
Write a manual Debug impl with debug_struct to redact secrets and mark unlisted fields with finish_non_exhaustive instead of leaking them.
Code
use std::fmt;
struct ApiClient {
base_url: String,
token: String,
retries: u32,
}
impl fmt::Debug for ApiClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ApiClient")
.field("base_url", &self.base_url)
// 密钥只输出占位符,避免随 {:?} 泄漏进日志
.field("token", &"[redacted]")
// 省略号表示还有未列出的字段
.finish_non_exhaustive()
}
}
fn main() {
let client = ApiClient {
base_url: "https://api.example.com".into(),
token: "sk-secret-123".into(),
retries: 3,
};
println!("{:?}", client);
println!("{:#?}", client);
}Redacting with debug_struct
The manual Debug impl for ApiClient registers base_url normally, outputs the literal “[redacted]” for token, and calls finish_non_exhaustive() so unlisted fields (retries) appear as the trailing .. marker. The println!(“{:?}”) line shows the single-line form; println!(“{:#?}”) the pretty one.
Why not derive
A derived Debug would print the raw token sk-secret-123 into any log that formats the client with {:?} — the hand-written impl is the firewall between internal state and diagnostics.
What finish_non_exhaustive adds
Without it, readers could assume the output lists every field; the .. suffix declares the struct has more fields than shown.
Interactive Tools for This Topic
FAQ
- Why write a manual Debug impl instead of deriving one?
- A derived impl would print the real token; the manual impl substitutes "[redacted]" so secrets never reach log output.
- What does finish_non_exhaustive() signal?
- That the Debug output intentionally omits fields, printed as a trailing .. so readers know the listing is partial.
Report a problem with this exampleOpens a pre-filled issue on GitHub.