Any magic to find out whether type X implements some triats T at compile time?

When I write a derive proc-macro, I need to generates a method for each field of struct, which returns true if the type of the field implements a trait T, else returns false. Is any way to do this?

I treid some ways, but found that I can't specialize code based on whether T impl or not impl trait.

pub trait T {}
pub struct X;  // implements T
pub struct Y;  // doesn't implement T
impl X for T { }

type Z = X;
#[derive(MySillyDerive)]
struct Foo {
   val1: Z,   // users can define type aliases, so we can't rely on the name of type
   val2: Y,
}

// Want to generates something like this
impl Foo {
  fn is_val1_implement_t() -> bool {  // TODO: always return true
  }
  fn is_val2_implement_t() -> bool {  // TODO: always return false
  }
}

Unfortunately, that step happens after macro expansion.

You can make those methods at compile time and hope they optimize away, but I don't know of any stable way to make them const, i.e., callable at compile time. I can't tell if that's sufficient for your use case or not.

Example.

1 Like

Wonderful solution !!!!

The basic idea is using same method name, but one is provided by type itself, while another is provided by a extension trait.

One more question, for ImplType<X>, both methods should be available, is there some document to clarify the rules to tell us which method will be chosen?

Inherent methods are preferred over trait methods, if that's what you are asking.

Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.