dongxiangchan0743 2018-07-26 18:44
浏览 19
已采纳

是否可以对反引号键入assert?

I want to implement logic branching depending on whether the input is a string or a backtick.

If it's a string I'll do a simple comparison of the input to an expected value, but if the input is a backtick (e.g. `foo\d{1,3}`) then I want to check my expected value against the input using something like regexp.MatchString instead.

So my question is: can you type assert against an input to check if it's a backtick or a standard string type?

Update: or even more specifically, I want to use a string function if I'm dealing with a string type and a regex function if I'm dealing with a regexp type

Thanks!

  • 写回答

1条回答 默认 最新

  • doutuan8887 2018-07-26 19:13
    关注

    No, you can't differentiate strings made with "" or ``.

    Sounds like you want to use either string or regexp type:

    1. You could pass interface and switch on type
    2. You could use string type and delimiters like // to indicate a regexp
    3. You could write two functions which do different things and take different params
    4. You could hold both in a struct and only use the regexp if filled in

    Hard to know which is best without knowing what problem you're trying to solve, but you probably don't want to use interface{} or just string and lose type safety. So taking option 4 you could for example have something like this:

    https://play.golang.org/p/Y5e3URTRFIR

    type Pattern struct {
        pattern string
        regexp  *regexp.Regexp
    }
    
    func (p Pattern) Match(input string) bool {
        if p.regexp != nil {
            return p.regexp.MatchString(input)
        }
    
        return input == p.pattern
    }
    
    func main() {
        patt := Pattern{pattern: "hello"}
        fmt.Printf("Matching string:%v
    ", patt.Match("hello"))
    
        rpatt := Pattern{pattern: 
        "hello",regexp:regexp.MustCompile("hello\\d{3}")}
        fmt.Printf("Matching regexp:%v
    ", rpatt.Match("hello123"))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器