Created
June 23, 2022 08:10
-
-
Save PeteGabriel/bfcd86927f292fe4627ddd2827112e09 to your computer and use it in GitHub Desktop.
This file contains 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" | |
/* | |
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