Vector {AbstractString}函数参数将不接受julia中的Vector {String}输入 [英] Vector{AbstractString} function parameter won't accept Vector{String} input in julia
本文介绍了Vector {AbstractString}函数参数将不接受julia中的Vector {String}输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Julia中的以下代码:
The following code in Julia:
function foo(a::Vector{AbstractString})
end
foo(["a"])
出现以下错误:
ERROR: MethodError: no method matching foo(::Array{String,1})
Closest candidates are:
foo(::Array{AbstractString,1}) at REPL[77]:2
即使按预期运行了以下代码:
Even though the following code runs, as expected:
function foo(a::Vector{String})
end
foo(["a"])
此外,AbstractString
通常与String
匹配,如下所示:
And further, AbstractString
generally matches String
as in:
function foo(::AbstractString)
end
foo("a")
如果我有String
个元素,如何使用Vector{AbstractString}
参数调用函数?
How can I call a function with a Vector{AbstractString}
parameter if I have String
elements?
推荐答案
您需要这样编写函数签名:
You need to write the function signature like this:
function foo{S<:AbstractString}(a::Vector{S})
# do stuff
end
在Julia 0.6及更高版本上,也可以改写
On Julia 0.6 and newer, it's also possible to write instead
function foo(a::Vector{<:AbstractString})
# do stuff
end
这是Julia中参数类型不变的结果.请参见有关类型的章节有关详细信息,请参见手册.
This is a consequence of parametric type invariance in Julia. See the chapter on types in the manual for more details.
这篇关于Vector {AbstractString}函数参数将不接受julia中的Vector {String}输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文