Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

println!() only if object implements Debug trait

Tags:

rust

I have method in my struct, that takes generic type T. The type may implement Debug trait, but it is not required by my struct.
I need to debug my application, and having the possibility to print it would be very useful. Unfortunately, I can't do it as the type may not implement Debug trait. I could specify the T: Debug in my struct definition, but I need to add it in a lot of places for my code to compile. Is it possible to invoke println!() macro only when the type implements this trait?

Something like this:

if argument.implements(Debug) {
    println!("{:?}", argument);
}
like image 772
Djent Avatar asked Sep 18 '25 06:09

Djent


1 Answers

It is currently not possible. Using any trait requires the enclosing function to have that constraint.

However, this will be possible when trait specialization is stabilized. The debugit crate for example provides conditional debug printing when compiled with nightly.

like image 74
kmdreko Avatar answered Sep 19 '25 19:09

kmdreko