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 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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值