简体   繁体   English

参数复合类型中的恢复类型

[英]Recover 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 T from an instance of that type? 在Julia(<0.6)中,当创建参数复合类型(如MyType{T} ,是否有一种从该类型的实例中恢复T的简洁方法?

Take their example from the doc: 以他们的文档为例:

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

I can create an object p = Point(5.0,5.0) , T here will be matched to Float64 so that the corresponding object is a Point{Float64} . 我可以创建一个对象p = Point(5.0,5.0) ,这里T将与Float64匹配,以便相应的对象是Point{Float64} Is there a clean way to recover Float64 here? 有一个干净的方法来恢复Float64吗?

I could do 我可以做

typeof(p.x)

But it feels like that's not the right thing to do. 但感觉这不是正确的事情。

When you need the type parameter, you should define a parametric method. 如果需要type参数,则应定义参数方法。 That is the only proper way to access the type parameter. 这是访问type参数的唯一正确方法。

So for a Point , 所以对于一个Point

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

The type is saved in the class information: 类型保存在类信息中:

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

It's more general than writing a specific function for it, but I'm not sure it's considered official. 它比为它编写特定功能更为通用,但我不确定它是否被认为是正式的。

There's also fieldtype 还有fieldtype

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

Not sure how that's any better than just getting the type of the instance though. 不知道如何才能获得实例的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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