This is a creation in Article, where the information may have evolved or changed.
Today in the group saw someone wrote a Inaarry method, the main role is to determine whether an element in the slice, after reading, I feel that the method should have expanded space
So I wrote a contains method, can support Slice,array,map and other types
Package Mainimport ("Errors" "FMT" "reflect")//determines if obj is in target, the type supported by Target Arrary,slice,mapfunc contain (obj interface{}, Target interface{}) (bool, error) {targetvalue:=reflect. ValueOf (target)Switchreflect. TypeOf (target). Kind () { Casereflect. Slice, reflect. Array: forI: = 0; I < Targetvalue.len (); i++ { ifTargetvalue.index (i). Interface () = =obj {return true, Nil}} Casereflect. Map:ifTargetvalue.mapindex (reflect. ValueOf (obj)). IsValid () {return true, Nil}} return false, errors. New ("Not in array")}func Main () {TestMap () Testarray () Testslice ()}func Testarray () {A:= 1B:= [3]int{1, 2, 3} fmt. Println (contain (a, b)) C:= "a"D:= [4]string{"B", "C", "D", "a"} fmt. Println (contain (c, D)) E:= 1.1F:= [4]float64{1.2, 1.3, 1.1, 1.4} fmt. Println (Contain (E, f)) G:= 1h:= [4]interface{}{2, 4, 6, 1} fmt. Println (Contain (g, h)) I:= [4]int64{} fmt. Println (contain (a, i))}func Testslice () {A:= 1B:= []int{1, 2, 3} fmt. Println (contain (a, b)) C:= "a"D:= []string{"B", "C", "D", "a"} fmt. Println (contain (c, D)) E:= 1.1F:= []float64{1.2, 1.3, 1.1, 1.4} fmt. Println (Contain (E, f)) G:= 1h:= []interface{}{2, 4, 6, 1} fmt. Println (Contain (g, h)) I:=[]int64{} fmt. Println (contain (a, i))}func TestMap () {varA = map[int]string{1: "1", 2: "2"} fmt. Println (Contain (3, a)) varb = map[string]int{"1": 1, "2": 2} fmt. Println (Contain ("1", B)) varc = map[string][]int{"1": {1, 2}, "2": {2, 3}} fmt. Println (Contain ("6", C))}