Created
March 20, 2022 18:43
-
-
Save massenz/08d378e491d4675f1a8f26a85e743a9f to your computer and use it in GitHub Desktop.
Go does not have a built-in `in` operator for slices
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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