是否可以对反引号键入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!

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"))
}