Skip to content

Instantly share code, notes, and snippets.

@PeteGabriel
Created June 23, 2022 08:10
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 PeteGabriel/bfcd86927f292fe4627ddd2827112e09 to your computer and use it in GitHub Desktop.
Save PeteGabriel/bfcd86927f292fe4627ddd2827112e09 to your computer and use it in GitHub Desktop.
package main
import "fmt"
/*
A function that received an array and a value
and returns true if the array contains the value
and false if the value is missing.
*/
//non-generic one
func ContainsInt(items []int, item int) bool {
for _, v := range items {
if v == item {
return true
}
}
return false
}
//make it generic. Types should be able to "compare"
//between themselves.
func Contains[T comparable](items []T, item T) bool {
for _, v := range items {
if v == item {
return true
}
}
return false
}
func main() {
fmt.Println(Contains[string]([]string{"boo", "far"}, "bar")) //false
fmt.Println(Contains[string]([]string{"boo", "far"}, "far")) //true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment