使用反射在运行时枚举结构的字段 [英] Using reflection to enumerate through the fields of a struct at runtime

查看:60
本文介绍了使用反射在运行时枚举结构的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的数据结构:

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?

推荐答案

实际上,有一种方法(ab)使用 可编码 Serialize 特征获取有关结构内容的反射信息(虽然不是方法)。

In fact, there is a way to (ab)use Encodable or Serialize traits to obtain reflection-like information about structure contents (not methods, though).

可编码 / 序列化主要用于编写序列化表示的结构,例如JSON对象。对于其内容的任何结构,它们的实现都可以自动生成(例如,使用#[derive(RustcEncodable)] 来生成 Encodable

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.

这些特征的实现会捕获有关结构的信息,并将其传递给 Encoder Serializer 。后一种特性的实现者通常使用此信息(字段名称,类型和值)来序列化对象,但是您当然可以编写自己的 Encoder / Serializer 即可根据需要使用此信息。我这里没有提供这种实现的示例,因为它们往往是样板形式的,但是您可以通过上面的链接找到一些实现。

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.

限制是您为了获取有关字段的信息,总是需要一个结构的值。您不仅可以获取任意类型的字段列表,例如Java反射允许。我认为可以编写 Encoder / Serializer 和一个内部不安全的实现功能类似于 fn type_info< T:Encodable>()-> TypeInfo 通过创建相应类型的未初始化内存并运行其 Encodable 方法来收集有关类型的信息,但我不是100 %对此有把握。

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.

这篇关于使用反射在运行时枚举结构的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆