Monday, 13 May 2019

Go language: Check for the existence of element in array or slice


Approach 1: Iterate over array or slice and return true when the element found
func isElementExist(ele string, arr []string) bool {
    for _, data := range arr {
        if data == ele {
            return true
        }
    }

    return false
}

App.go
package main

import "fmt"

func isElementExist(ele string, arr []string) bool {
    for _, data := range arr {
        if data == ele {
            return true
        }
    }

    return false
}

func main() {
    exist := isElementExist("Krishna", []string{"Hari", "Krishna", "Ram", "Chamu"})

    fmt.Println("Is Krishna exists in array : ", exist)
}

Output
Is Krishna exists in array :  true

Approach 2: Using Map as set
If you don’t want to iterate over the array every time, then by storing all the elements as keys in map, you can check for the existence of element.


App.go
package main

import "fmt"

func main() {
    employeeNames := make(map[string]bool)

    employeeNames["Hari"] = true
    employeeNames["Krishna"] = true
    employeeNames["Ram"] = true
    employeeNames["Chamu"] = true

    fmt.Println("Is Krishna exists in array : ", employeeNames["Krishna"])
}

Output
Is Krishna exists in array :  true





Previous                                                 Next                                                 Home

No comments:

Post a Comment