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"))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)