The problem of implementing in_array in go language

problem description

the problem of implementing in_array in GO language, that is, judging whether a value exists in slice

the environmental background of the problems and what methods you have tried

related codes

/ / Please paste the code text below (do not replace the code with pictures)

func main()  {
    str1 := "dd"
    strArr := []string{"aa","bb","cc","dd"}   
    exists := inArray(str1, strArr)
    fmt.Println(exists)
}


func inArray(need interface{}, needArr []interface{}) bool {
     for _,v := range needArr{
        if need == v{
            return true
        }
    }
    return false
}

what result do you expect? What is the error message actually seen?

  need needArr slicetruefalse

:
-sharp command-line-arguments

srctestinarray.go:14:19: cannot use strArr (type [] string) as type [] interface {} in argument to inArray


this is a misunderstanding of the basic syntax. The
inArray function parameter type is [] interface {} means that the element type is interface {} , which means that each element can be of a different type, such as a: = [] interface {} {"test", 123, mapping [int] string {2: "bb"}} .
and if you pass in a specified type like your [] string {} , then every element in the slice must be of type string , which obviously does not match the meaning of the formal parameter [] interface {} of inArray.
therefore, the argument type must also be [] interface {} , where the element can be of any type.


func main()  {
    str1 := "dd"
    strArr := []string{"aa","bb","cc","dd"}
    exists := inArray(len(strArr), func(i int) bool {return strArr[i] == str1})
    fmt.Println(exists)
}

func inArray(n int, f func(int) bool) bool {

    for i := 0; i < n; iPP {
       if f(i) {
          return true
       }
    }
    return false
}

to find this thing, only the comparison function is related to the type, and the algorithm logic itself has nothing to do with the type, so taking the comparison function as a parameter can achieve the effect of a general algorithm.


func maim() {
    var (
        str1   interface{}
        strArr []interface{}
    )
    str1 = "dd"
    strArr = []interface{}{"aa", "bb", "cc", "dd"}
    exists := inArray(str1, strArr)
    fmt.Println(exists)
}

func inArray(need interface{}, needArr []interface{}) bool {
    for _, v := range needArr {
        if need == v {
            return true
        }
    }
    return false
}

Go does not support generics. [] xx and [] interface {} are two types.

either write a script to generate a bunch of types of in_array, or sacrifice efficiency with reflect. Look at the scene.

wait for Go2


you can refer to this, and there are also some explanations in the article, from the official wiki

.
  Source  

Menu