Using reflection to enumerate through the fields of a struct at runtime

后端 未结 2 861
盖世英雄少女心
盖世英雄少女心 2021-01-24 02:06

If I have a data structure like this:

struct Point {
    x: i32,
    y: i32,
}

impl Point {
    fn setX(&mut self, x: i32) -> &mut Point {
        s         


        
相关标签:
2条回答
  • 2021-01-24 02:44

    Rust does not really support this kind of reflection at runtime, no.

    In theory, you might be able to write a syntax extension that would let you generate some code that would do something like this, maybe...

    0 讨论(0)
  • 2021-01-24 02:59

    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.

    0 讨论(0)
提交回复
热议问题