Recovery type in parametric composite type

In Julia (<0.6), when creating a parametric composite type, such as MyType{T}, is there a clean way to recover Tfrom an instance of this type?

Take an example from the document:

type Point{T}
    x::T
    y::T
end

I can create an object p = Point(5.0,5.0), Tit will correspond here Float64so that the corresponding object is Point{Float64}. Is there a clean way to recover Float64here?

I could do

typeof(p.x)

But it seems like it is not.

+4
source share
3 answers

When you need a type parameter, you must define a parametric method. This is the only correct way to access the type parameter.

, a Point,

function doSomething{T}(p::Point{T}) 
    // You have recovered T  
    println(T)
end
+10

:

typeof(Point(1, 2)).parameters # -> svec(Int64)

, , , .

+1

There also fieldtype

fieldtype(typeof(Point(1.0, 1.0)), :x) # --> Float64
fieldtype(Point, :x) # --> T
fieldtype(Point{Int64}, :x) # --> Int64

Not sure if this is better than just getting an instance type.

0
source

Source: https://habr.com/ru/post/1672717/


All Articles