Using reflection to enumerate through the fields o

2019-08-10 01:56发布

If I have a data structure like this:

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

impl Point {
    fn setX(&mut self, x: i32) -> &mut Point {
        self.x = x;
        self
    }
}

Is it possible to iterate through Point and see both each member and the name of each member?

Is it also possible to go through the implementation and see what each function's name is?

Is it possible to do the above two tasks at runtime, without special implementations?

2条回答
The star\"
2楼-- · 2019-08-10 02:29

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...

查看更多
别忘想泡老子
3楼-- · 2019-08-10 02:43

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.

查看更多
登录 后发表回答