Skip to content

Instantly share code, notes, and snippets.

@massenz
Created March 20, 2022 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save massenz/08d378e491d4675f1a8f26a85e743a9f to your computer and use it in GitHub Desktop.
Save massenz/08d378e491d4675f1a8f26a85e743a9f to your computer and use it in GitHub Desktop.
Go does not have a built-in `in` operator for slices
package main
import "fmt"
// Tempting, but this will NOT compile
//
//func (arr []interface{}) Has(x interface{}) bool {
// for _, val := range arr {
// if val == x {
// return true
// }
// }
// return false
//}
// IsIn will work, sort of, if you're prepared to put up with a lot of nonsense
func IsIn(x interface{}, arr []interface{}) bool {
for _, val := range arr {
if val == x {
return true
}
}
return false
}
func main() {
// When I said "nonsense", I wasn't kidding
var x []interface{}
x = make([]interface{}, 0, 10)
x = append(x, 3)
x = append(x, 4)
x = append(x, 5)
fmt.Println(IsIn(4, x))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment