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