Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

invariance - Vector{AbstractString} function parameter won't accept Vector{String} input in julia

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...