How do I get the subtype of an instance of an parametric type in julia? For example:
immutable Dog{T <: Number}
snout::T
end
dog = Dog(5.)
typeof(dog)
...returns Dog{Float64}
. Is there a way to get at the type Float64
from the variable dog
without referring explicitly to the field snout
?
type and immutable are valid up to julia 0.6, mutable struct and struct are the names of the same objects in julia 0.6 and forward. mutable in mutable struct means that the fields can change - which is actually fairly rarely used so being immutable is the default. mutable struct 's are slower than struct s.
It depends on your use case. If you are interested in a specific case like this, a good way is to define a function
dogtype{T}(::Dog{T}) = T
Then dogtype(Dog(.5))
will give you Float 64
.
This is the kind of pattern that is used to implement the eltype
function in base Julia.
This works for me:
julia> VERSION
v"0.4.0-dev+5733"
julia> immutable Dog{T <: Number}
snout::T
end
julia> dog = Dog(0.5)
Dog{Float64}(0.5)
julia> typeof(dog).parameters[1]
Float64
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