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 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化