3

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?

hedgar2017
  • 1,425
  • 3
  • 21
  • 40
  • I believe your question is answered by the answers of [Is it possible to check if an object implements a trait at runtime?](https://stackoverflow.com/q/30274091/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Aug 12 '18 at 19:29
  • You may also be interested in [Rust generic trait implementations for trait](https://stackoverflow.com/q/42426239/155423). – Shepmaster Aug 12 '18 at 19:32
  • As well as [How can I implement a function differently depending on if a generic type implements a trait or not?](https://stackoverflow.com/q/51141200/155423). – Shepmaster Aug 12 '18 at 19:36
  • Runtime checking is not needed. Compile-time only. – hedgar2017 Aug 12 '18 at 19:48
  • How does it differ from the other questions? – Shepmaster Aug 12 '18 at 19:49
  • 2
    I think the other questions are not related. I need only a macro (not a function) that prints a variable with either Display or Debug if Display is not implemented. – hedgar2017 Aug 12 '18 at 19:53
  • 2
    Macros expand to code and at the time they are expanded, type information isn't available yet. So a macro wouldn't help. Any ways, if you want to format using either `Display` or `Debug`, it probably means you just want `Debug`. – mcarton Aug 12 '18 at 20:01
  • 1
    @Boiethios, duplicate it is. Fits my question. – hedgar2017 Aug 12 '18 at 20:20
  • @mcarton, I have just created separate macros. I needed to implement stuff described above for DHCP options. There are around 150 of them, so I won't overload each, especially when the majority of them are complex types like `Vec<(IpV4Addr, IpV4Addr>`. – hedgar2017 Aug 13 '18 at 07:40
  • 7
    I'd say this is not a duplicate. Compile time != run time. I'm trying to figure out how to assert at compile time that a variable implements a trait. Which is similar, but not quite the same question. :( – LordCecil May 20 '19 at 06:52

1 Answers1

1

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>();
}
MrBigglesworth
  • 350
  • 1
  • 8