Use the secrecy crate to wrap sensitive values in a Secret type that prevents accidental logging or printing. Add the dependency, import the macro, and wrap your data to enforce compile-time safety against leaks.
use secrecy::{Secret, ExposeSecret};
fn main() {
let password = Secret::new("hunter2".to_string());
// println!("Password: {}", password); // Compile error!
let exposed: &str = password.expose_secret();
println!("Password: {}", exposed); // Explicit access only
}
- Add the crate to your
Cargo.tomlfile.cargo add secrecy - Import the
Secretstruct andExposeSecrettrait in your source file.use secrecy::{Secret, ExposeSecret}; - Wrap your sensitive string or value using the
Secret::newconstructor.let secret = Secret::new("my_password".to_string()); - Access the underlying value only when explicitly needed using the
expose_secretmethod.let plain = secret.expose_secret(); - Attempting to print or format the
Secretdirectly will now fail at compile time.// println!("{}", secret); // Error: Secret does not implement Display