Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Search for an element in slice in Go

SearchStrings method can be used to find the element's index. If the element is not found in the slice then the length of the slice is returned, this is different in Go Lang compared to other languages where -1 value is returned.

Syntax
sort.SearchStrings(sliceName, "value to search")


Example : Search for an element in slice
import (
    "fmt"
    "sort"
)

func main() {

    personNameSlice := make([]string, 0)

    personNameSlice = append(personNameSlice, "hello")

    personNameSlice = append(personNameSlice, "world")

    searchedIndex := sort.SearchStrings(personNameSlice, "world")

    if searchedIndex < len(personNameSlice) {
        fmt.Printf("Element is found in index %d \n", searchedIndex)
    } else {
        fmt.Printf("Element not found")
    }
}


Output
Element is found in index 1