Golang : Check String In Arrays / String Contain In Array

Instead of using a slice, map may be a better solution. simple example:


package main

import "fmt"

func contains(slice []string, item string) bool {
	set := make(map[string]struct{}, len(slice))
	for _, s := range slice {
		set[s] = struct{}{}
	}
	_, ok := set[item]
	return ok
}

func main() {

    s := []string{"a", "b"}
    s1 := "a"
    fmt.Println(contains(s, s1))

}

author image

Founder of tarkiman.com, love programming and open source stuff. Subscribe him on Youtube Channel.

Comments