代码之家  ›  专栏  ›  技术社区  ›  daycaster

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

  •  2
  • daycaster  · 技术社区  · 7 年前

    鉴于:

    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 回复  |  直到 7 年前
        1
  •  2
  •   Mark Birtwistle    7 年前

    我认为有两种方法可以做到这一点:

    1. 使用 AbstractString 而不是 String 在功能定义中;

    2. 定义函数两次,一次 字符串 还有一次 SubString ,它将生成 myfunction (generic function with 2 methods) 是的。

    关键是 子串 抽象字符串 ,不是 字符串 是的。你可以通过输入 supertype(SubString) 是的。