Julia 中 Type 类型

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mifangdebaise/article/details/85028699

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 Julia isa Type, only Int 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 of Number, and not the type of Int, even though Int <: 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 of T in particular.


强调一下加强理解,T 为一个类型(如 Int, Float64 等),那么 Type{T} 即为类型 T类型 (有点拗口,注意理解),TType{T} 唯一的实例:

julia> Int isa Type{Int}
true

猜你喜欢

转载自blog.csdn.net/mifangdebaise/article/details/85028699