-4

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!

Integralist
  • 5,899
  • 5
  • 25
  • 42
  • 2
    There is no difference, they're both strings. They're just different syntaxes for writing a string constant. Because they are the same type, there is no way at runtime to know how they were created. – Adrian Jul 26 '18 at 18:45
  • 3
    A `string` is a `string`. – peterSO Jul 26 '18 at 18:45
  • ok thanks for clarifying, but is there another way maybe to achieve what I'm describing? – Integralist Jul 26 '18 at 19:04
  • 1
    If you're trying to distinguish plain strings from regexes, you need to differentiate them within the strings somehow. How you do so is entirely up to you. If the actual input is read in with backticks or quotes, then you have your answer by comparing the strings. – JimB Jul 26 '18 at 19:12
  • 1
    This sounds like an XY Problem. What is your _actual_ goal? – Jonathan Hall Jul 27 '18 at 15:41

1 Answers1

1

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\n", patt.Match("hello"))

    rpatt := Pattern{pattern: 
    "hello",regexp:regexp.MustCompile("hello\\d{3}")}
    fmt.Printf("Matching regexp:%v\n", rpatt.Match("hello123"))
}
Kenny Grant
  • 9,360
  • 2
  • 33
  • 47