如何在Julia中查询将指定类型作为类型声明的结构体字段?
实现思路
Julia标准库没有提供直接查询「将指定类型作为字段类型的所有字段」的内置函数,你可以通过Julia自带的反射API自行实现该功能,核心逻辑是遍历目标范围内的所有类型,逐一检查每个类型的字段类型是否匹配目标类型。
通用查询函数实现
function find_fields_of_type(target_type, mod=Main) result = [] for name in names(mod, all=true) # 跳过Julia内部生成的带#前缀的标识符,以及未定义的名称 if startswith(string(name), '#') || !isdefined(mod, name) continue end obj = getproperty(mod, name) # 筛选出非参数化的具体类型 if obj isa Type && !(obj isa UnionAll) # 遍历当前类型的所有字段做匹配 for (idx, f_type) in enumerate(fieldtypes(obj)) if f_type == target_type push!(result, ( belong_type = obj, field_name = fieldname(obj, idx), field_type = f_type )) end end end end return result end
使用示例
针对你给出的结构体定义:
struct MyType end struct MyType2 attr::MyType end
调用查询函数即可得到结果:
julia> find_fields_of_type(MyType) 1-element Vector{Any}: (belong_type = MyType2, field_name = :attr, field_type = MyType)
扩展说明
- 默认只遍历
Main模块下的类型,如果你的类型定义在指定子模块中,调用函数时传入对应的模块作为第二个参数即可;如果需要查询所有已加载模块,可以扩展函数遍历Base.loaded_modules的所有模块 - 上述代码做精确类型匹配,如果需要支持子类型匹配(比如目标类型的子类型也纳入结果),可以把
f_type == target_type改为target_type <: f_type - 如果需要支持参数化类型的匹配,可以自行调整
obj isa Type && !(obj isa UnionAll)的过滤规则
内容的提问来源于stack exchange,提问作者ahm5
相关产品推荐
相关产品推荐

