Golang: search an array

Go is a pretty awesome language, typed, C-like, fast. I’m porting one of my python applications to Go. Searching an array isn’t as simple as it is in python though.

In Python you can use in or not in:

if self.args[1] not in self.valid_options:
    print("ERROR: valid options are %s" % self.valid_options)
    sys.exit(1)

Go doesn’t have membership operators, so you have to search the string for what you want. Then you get the index and see if it actually exists:

i := sort.SearchStrings(lc.valid_options, args[1])
if i >= len(lc.valid_options) ||
  i < len(lc.valid_options) && lc.valid_options[i] != args[1] {

  fmt.Printf("ERROR: valid options are %v\n", lc.valid_options)
  os.Exit(1)
}

Leave a comment