Vector{AbstractString} 函数参数在 julia 中不接受 Vector{String} 输入 [英] Vector{AbstractString} function parameter won't accept Vector{String} input in julia

查看:17
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆