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

Nae*_*mul 4 types casting covariance julia

我发现Array在Julia中不是协变的,并且子类型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]可以.

朱莉娅有这种行为的原因吗?

fre*_*kre 5

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

head(a::Vector{<:Number}) =...
Run Code Online (Sandbox Code Playgroud)