是否有可能获得形成联合的类型集合?

is it possible to get collection of types what form the union?

假设我有 Union:

    SomeUnion = Union{Int, String}

有没有一种方法可以提取构成该联合的类型集合?例如....

    union_types(SomeUnion) # => [Int, String]

在这里写一个简单的例子:

a = Union(Int,String)

function union_types(x)
  return x.types
end

julia> union_types(a)
(Int64,String)

如果需要,您可以将结果存储到数组中:

function union_types(x)
    return collect(DataType, x.types)
end

julia> union_types(a)
2-element Array{DataType,1}:
 Int64 
 String

更新:按照@Luc Danton 在下面评论中的建议使用collect

对于 Julia 0.6,NEWS.md 声明“Union 类型有两个字段,ab,而不是单个 types 字段” .此外,"Parametric types with "未指定的“参数,例如 Array,现在表示为 UnionAll 类型而不是 DataTypes”。

因此,要将类型作为元组获取,可以这样做

union_types(x::Union) = (x.a, union_types(x.b)...)
union_types(x::Type) = (x,)

如果你想要一个数组,只需 collect 元组

julia> collect(union_types(Union{Int, Float64, String, Array}))
4-element Array{Type,1}:
 Int64  
 Float64
 String
 Array

Base.uniontypes 未记录(截至 julia-1.6.1),因此请谨慎使用。 但它有效:

julia> SomeUnion = Union{Int, String}
Union{Int64, String}

julia> Base.uniontypes(SomeUnion)
2-element Vector{Any}:
 Int64
 String