简体   繁体   中英

How to extract the specific type from an instance of a generic type in julia?

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 ?

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

No, because the type of dog is Dog{Float64} not Float64 . Think of what would be the expected output if you parametrize Dog by more than one type.

The recommended way is to use a method to access a type/immutable fields:

julia> type Foo{T <: Number, S <: AbstractString}
           bar::T
           baz::S
       end

julia> foo = Foo(5.5, "test")
Foo{Float64,ASCIIString}(5.5,"test")

julia> typeof(foo)
Foo{Float64,ASCIIString}

julia> typeof(foo.bar)
Float64

julia> typeof(foo.baz)
ASCIIString

julia> for field in names(Foo)
           @eval $(field)(x::Foo) = x.$field
       end

julia> typeof(bar(foo))
Float64

julia> typeof(baz(foo))
ASCIIString

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