鉴于:
julia> SubString <: String
false
您将如何编写同时接受子字符串和字符串的函数?
julia> function myfunction(ss::String)
@show ss, typeof(ss)
end
myfunction (generic function with 1 method)
julia> myfunction("Hello World")
(ss, typeof(ss)) = ("Hello World", String)
("Hello World", String)
julia> s = split("Hello World")
2-element Array{SubString{String},1}:
"Hello"
"World"
julia> foreach(x -> myfunction(x), s)
ERROR: MethodError: no method matching myfunction(::SubString{String})
Closest candidates are:
myfunction(::String) at REPL[11]:2
答案 0 :(得分:2)
我认为您可以通过两种方式进行此操作:
在函数定义中使用AbstractString
而不是String
;
两次定义函数,一次为String
,一次为SubString
,这将生成myfunction (generic function with 2 methods)
。
重点是SubString
是AbstractString
的子类型,而不是String
。您可以输入supertype(SubString)
来看到此内容。