Search code examples
reflectionrustpolymorphismoutputtraits

How do I check if a trait is implemented at compile time in Rust?


I want to print a variable with the Display trait if it is implemented, or with the Debug trait otherwise. All the types are known at compile time.

let display = MyDisplayType::new(); // implements Display
let debug = MyDebugType::new(); // implements Debug

output!(display); // uses Display a.k.a. println!("{}", display);
output!(debug); // uses Debug a.k.a. println!("{:?}", debug);

What is the cleanest way?


Solution

  • It's possible if you want to assert that a type, at compile time, implements a trait. For example in a unit test you can create a function bounded for the trait. If the type doesn't implement the trait, the code will not compile.

    fn implements_the_trait<T: MyTrait>() {}
    
    #[test]
    fn implements_my_trait() {
      implements_the_trait::<MyType>();
    }