Julia 中 Type 型別
Julia
中還有一個基本的型別:Type
,其實我們知道 Julia
文件中 已宣告的型別 這一節中提到了 DataType
這一基本資料型別,但是還有一個 Type
型別,這兩個型別之間的差別可以參見 Julia: Diffrence between Type and DataType
這裡我們只舉出 Type
型別的一種常見用法: Type{T}
(引用來自 Julia: Diffrence between Type and DataType ):
Type
is special. As you see above, it’s parametric. This allows you to precisely specify the type of a specific type in question. So while every single type in Juliaisa
Type, onlyInt
isa
Type{Int}
:julia> isa(Int, Type{Int}) true julia> isa(Float64, Type{Int}) false julia> isa(Float64, Type) true
This ability is special and unique to
Type
, and it’s essential in allowing dispatch to be specified on a specific type. For example, many functions allow you to specify a type as their first argument.f(x::Type{String}) = "string method, got $x" f(x::Type{Number}) = "number method, got $x" julia> f(String) "string method, got String" julia> f(Number) "number method, got Number"
It’s worth noting that
Type{Number}
is only the type ofNumber
, and not the type ofInt
, even thoughInt <: Number
! This is parametric invariance. To allow all subtypes of a particular abstract type, you can use a function parameter:julia> f(Int) ERROR: MethodError: no method matching f(::Type{Int64}) julia> f{T<:Integer}(::Type{T}) = "integer method, got $T" f (generic function with 3 methods) julia> f(Int) "integer method, got Int64"
The ability to capture the specific type in question as a function parameter is powerful and frequently used. Note that I didn’t even need to specify an argument name — the only thing that matters in this case is the parameter within
Type{}
.
Use
Type{T}
when you want to describe the type ofT
in particular.
強調一下加強理解,T
為一個型別(如 Int
, Float64
等),那麼 Type{T}
即為型別 T
的型別 (有點拗口,注意理解),T
為 Type{T}
唯一的例項:
julia> Int isa Type{Int}
true