为什么 Array{Float64, N} 不能作为参数为 Array{Number, N} 的函数的参数?

Why Array{Float64, N} cannot be a parameter of a function whose parameter is Array{Number, N}?

我发现 Julia 中的 Array 不是协变的,Number 的子类型不会自动转换为超类型。

我的意思是,比如,

head(a::Vector{Number}) = a[1]head(a::Vector{Real}) = a[1]

无法执行 head([1, 2, 3]),

head(a::Vector{T}) where {T <: Number} = a[1]head(a::Vector{T}) where {T <: Real} = a[1] 可以。

Julia 中有这种行为的原因吗?

请参阅手册中的此部分:https://docs.julialang.org/en/stable/manual/types/#Parametric-Composite-Types-1 其中对此进行了解释。请注意,head(a::Vector{T}) where {T <: Number} =... 有一个缩写形式(除非您在函数体中使用 T,否则您可以使用它):

head(a::Vector{<:Number}) =...