Vector{AbstractString} function parameter won'

2019-01-19 15:39发布

The following code in Julia:

function foo(a::Vector{AbstractString})  
end
foo(["a"])

gives the following error:

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"])

And further, AbstractString generally matches String as in:

function foo(::AbstractString)  
end
foo("a")

How can I call a function with a Vector{AbstractString} parameter if I have String elements?

1条回答
霸刀☆藐视天下
2楼-- · 2019-01-19 16:02

You need to write the function signature like this:

function foo{S<:AbstractString}(a::Vector{S})
    # do stuff
end

On Julia 0.6 and newer, it's also possible to write instead

function foo(a::Vector{<:AbstractString})
    # do stuff
end

This is a consequence of parametric type invariance in Julia. See the chapter on types in the manual for more details.

查看更多
登录 后发表回答