Showing posts with label go slice. Show all posts
Showing posts with label go slice. Show all posts

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

Thursday, 2 May 2019

Go language: Append an element to a slice


‘append’ method is used to append an element to a slice.

Example
var vowels = []string{"a", "e", "i"}
vowels = append(vowels, "o")

App.go
package main

import "fmt"

func main() {

 var vowels = []string{"a", "e", "i"}

 vowels = append(vowels, "o")
 vowels = append(vowels, "u")

 fmt.Println(vowels)

}

Output
[a e i o u]



Previous                                                 Next                                                 Home