是否有可能获得什么形式的联合类型的集合?

Ole*_*yba 5 julia

假设我有Union:

    SomeUnion = Union{Int, String}
Run Code Online (Sandbox Code Playgroud)

有没有一种方法来提取形成这种联合的类型集合?例如 ....

    union_types(SomeUnion) # => [Int, String]
Run Code Online (Sandbox Code Playgroud)

Gni*_*muc 5

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

a = Union(Int,String)

function union_types(x)
  return x.types
end

julia> union_types(a)
(Int64,String)
Run Code Online (Sandbox Code Playgroud)

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

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

julia> union_types(a)
2-element Array{DataType,1}:
 Int64 
 String
Run Code Online (Sandbox Code Playgroud)

更新:使用collect@Luc Danton在下面的评论中提出.

  • `collect(DataType,a.types)`可以是一种简洁的方法,将类型收集到一个数组中. (3认同)