Golang General contains method

Source: Internet
Author: User
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))}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.