鉴于:
julia> SubString <: String
false
Run Code Online (Sandbox Code Playgroud)
你将如何编写一个接受子字符串和字符串的函数?
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
Run Code Online (Sandbox Code Playgroud)
我认为有两种方法可以做到这一点:
在函数定义中使用AbstractString
而不是;String
定义该函数两次,一次 for String
,一次 for SubString
,这将生成myfunction (generic function with 2 methods)
.
关键是SubString
是 的子类型AbstractString
,而不是String
。您可以通过输入来看到这一点supertype(SubString)
。