In fact, there is a way to (ab)use Encodable
or Serialize
traits to obtain reflection-like information about structure contents (not methods, though).
Encodable
/Serialize
are used primarily for writing a structure to some serialized representation, e.g. a JSON object. Their implementations can be automatically generated (e.g. with #[derive(RustcEncodable)]
for Encodable
) for any structure whose contents also implement corresponding trait.
Implementations of these traits capture information about the structure and they pass it to an implementation of Encoder
or Serializer
. Implementors of the latter traits usually use this information (field names, types and values) to serialize objects but of course you can write your own implementation of Encoder
/Serializer
which will do with this information whatever you want. I'm not providing an example of such implementation here because they tend to be boilerplate-y, but you can find some through the links above.
The limitation is that you always need a value of a structure in order to get information about fields. You can't just get a list of fields of an arbitrary type, like e.g. Java reflection allows. I think it is possible to write an internally unsafe implementation of Encoder
/Serializer
and a function like fn type_info<T: Encodable>() -> TypeInfo
which collects information about a type by creating an uninitialized piece of memory of the corresponding type and running its Encodable
methods, but I'm not 100% sure about this.
pub
struct fields. And perhaps a tuple struct. – Mildamilde