我发现Array
在 Julia 中不是 Number
的协变和子类型不会自动转换为父类(super class)型。
我的意思是,例如,
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}) =...
关于types - 为什么 Array{Float64, N} 不能作为参数为 Array{Number, N} 的函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51474530/