同时使用字符串和子字符串

时间:2018-07-01 12:50:02

标签: julia

鉴于:

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

1 个答案:

答案 0 :(得分:2)

我认为您可以通过两种方式进行此操作:

  1. 在函数定义中使用AbstractString而不是String

  2. 两次定义函数,一次为String,一次为SubString,这将生成myfunction (generic function with 2 methods)

重点是SubStringAbstractString的子类型,而不是String。您可以输入supertype(SubString)来看到此内容。