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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With