简体   繁体   中英

Get parameters of a parametric type

Suppose I define a type like that

type Point{Tx, Ty} end

Then I create a variable of this type, for example,

a = Point{Int64, :something}()

Now, I only know that I can get the type of a by typeof(a) . That is, Point{Int64, :something} . But, what I need is just the parameters Tx and Ty .

Are there ways that I can get those parameters Tx and Ty ?

You can define a function as follows

eltypes{Tx,Ty}(::Type{Point{Tx, Ty}}) = (Tx, Ty)
eltypes(p) = eltypes(typeof(p))

(here ::Type{Point{Tx, Ty}} matches an argument of type Point{Tx, Ty} ) and use it

julia> eltypes(Point{Int, Float64}())
(Int64,Float64)

This is a frequently used idiom, for example in Base there is the similar function

eltype{T}(::Type{Set{T}}) = T
eltype(x) = eltype(typeof(x))

typeof(a) is a DataType which has many fields. you can get those names via:

julia> fieldnames(DataType)
10-element Array{Symbol,1}:
 :name        
 :super       
 :parameters  
 :types       
 :instance    
 :size        
 :abstract    
 :mutable     
 :pointerfree 
 :ninitialized

so if you need those parameters, run

julia> collect(typeof(a).parameters)
2-element Array{Any,1}:
 Int64     
 :something

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM