【发布时间】:2018-10-30 14:53:38
【问题描述】:
我正在尝试通过阅读文档来学习 Julia,他们的代码如下所示:
function testFunction(x::Number)
return x+5
end
这是一个适用于 Juila 中任何一种数字类型的函数。
但是,如果我尝试做类似的事情,像这样:
function testFunction2(x::Array{Number})
return x
end
我收到以下错误:
ERROR: MethodError: no method matching testFunction2(::Array{Int64,1})
Closest candidates are:
testFunction2(::Array{Number,N} where N) at /Users/.../Desktop/Test.jl:45
我做错了吗?我认为:Array{Float64} 是您声明特定类型数组的方式,但使用类似Number 的类型(适用于常规情况)在这里不起作用......任何见解都值得赞赏。
【问题讨论】:
-
testFunction2应声明为:function testFunction2(x::Array{<:Number})(与<:),因为 Array{Float64} 不是 Array{Number}。见:Type inheritance in function arguments -
Julia 的类型系统是不变的。这在this section of the docs 中有详细介绍(特别是,请参阅突出显示的警告)