目录

GoLang检查数组中是否存在某个值

golang检查数组中是否存在某个值

  • 类似PHP用的in_array功能实现

    in_array(mixed $needle, array $haystack, bool $strict = false): bool

在Go 1.18 版本支持泛型以后,可以在pkg.go.dev中的slices包下查找Contains方法用作实现,例如:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import (
 "fmt"

 "golang.org/x/exp/slices"
)

func main() {
    var date string = "createdAt"
    dateType := []string{"createdAt", "updatedAt"}
    if slices.Contains[string](dateType, date) {
        fmt.Println("yes")
    } else {
        fmt.Println("no")
    }
}