Golang array contains specific element or not? [SOLVED]


GOLANG Solutions, GO

Author: Tuan Nguyen
Reviewer: Deepak Prasad

In this tutorial we will cover different methods to check golang array contains specific provided element. We are going to cover following methods

 

Method-1: Using for loop

Some programming languages have a built-in method similar to indexOf() for determining the existence of a particular element in an array-like data structure. However, in Golang, there's no such method and we can simply implement it with the help of a for-range loop. We can iterate over the array, and check for the equality of values using the equal operator. If there is a match, we can stop the search and conclude that the element is in the array.

 

Example-1: Check array contains element without index details

In the below example, we have an array of strings, and we want to find out whether a given string exists in the array or not.

package main

import (
	"fmt"
)

// fuction to check given string is in array or not
func implContains(sl []string, name string) bool {
	// iterate over the array and compare given string to each element
	for _, value := range sl {
		if value == name {
			return true
		}
	}
	return false
}
func main() {
	names := []string{"Ana", "Bob", "Clair", "Daniel", "Fred", "Hush", "Timmy"}

	// some string to check
	nameCheck1 := "Milley"
	nameCheck2 := "Bob"
	nameCheck3 := "bob"

	isPresent1 := implContains(names, nameCheck1)
	isPresent2 := implContains(names, nameCheck2)
	isPresent3 := implContains(names, nameCheck3)

	if isPresent1 {
		fmt.Println(nameCheck1, "is in the names array")
	} else {
		fmt.Println(nameCheck1, "is not in the names array")
	}

	if isPresent2 {
		fmt.Println(nameCheck2, "is in the names array")
	} else {
		fmt.Println(nameCheck2, "is not in the names array")
	}

	if isPresent3 {
		fmt.Println(nameCheck3, "is in the names array")
	} else {
		fmt.Println(nameCheck3, "is not in the names array")
	}
}

Output:

Milley is not in the names array
Bob is in the names array
bob is not in the names array

 

Example-2: Check array contains element along with index number

Consider the shown below code if you want to return the index at which we have encountered the given element

package main

import (
	"fmt"
)

// fuction to check given string is in array or not
func implContains(sl []string, name string) int {
	// iterate over the array and compare given string to each element
	for index, value := range sl {
		if value == name {
                        // return index when the element is found
			return index
		}
	}
        // if not found given string, return -1
	return -1
}
func main() {
	names := []string{"Ana", "Bob", "Clair", "Daniel", "Fred", "Hush", "Timmy"}

	// some string to check
	nameCheck1 := "Milley"
	nameCheck2 := "Bob"
	nameCheck3 := "bob"

	index1 := implContains(names, nameCheck1)
	index2 := implContains(names, nameCheck2)
	index3 := implContains(names, nameCheck3)

	if index1 != -1 {
		fmt.Println(nameCheck1, "is in the names array at index:", index1)
	} else {
		fmt.Println(nameCheck1, "is not in the names array")
	}

	if index2 != -1 {
		fmt.Println(nameCheck2, "is in the names array at index:", index2)
	} else {
		fmt.Println(nameCheck2, "is not in the names array")
	}

	if index3 != -1 {
		fmt.Println(nameCheck3, "is in the names array at index:", index3)
	} else {
		fmt.Println(nameCheck3, "is not in the names array")
	}
}

Output:

Milley is not in the names array
Bob is in the names array at index: 1
bob is not in the names array

 

Example-3: Check array contains float64 element

Noted that, with this method, if we want to check if a given float64 is in a float64 array or not, we have to re-write the function. Instead of that, we can use Go generics that takes the any data type of array and given element as arguments. Example:

package main

import (
	"fmt"
)

// fuction to check given string is in array or not
func implContains[T comparable](s []T, e T) bool {
	for _, v := range s {
		if v == e {
			return true
		}
	}
	return false
}

func main() {
	names := []string{"Ana", "Bob", "Clair", "Daniel", "Fred", "Hush", "Timmy"}

	// some string to check
	nameCheck := "Bob"
	isPresent1 := implContains(names, nameCheck)

	if isPresent1 {
		fmt.Println(nameCheck, "is in the names array")
	} else {
		fmt.Println(nameCheck, "is not in the names array")
	}

	scores := []float64{14.2, 26.5, 9.6, 36.4, 52.6}
	scoreCheck := 9.6

	isPresent2 := implContains(scores, scoreCheck)
	if isPresent2 {
		fmt.Println(scoreCheck, "is in the scores array")
	} else {
		fmt.Println(scoreCheck, "is not in the scores array")
	}

}

Output

Bob is in the names array
9.6 is in the scores array

 

Method-2: Using slices.Contains() function

Starting with Go 1.18, you can use the slices package – specifically the generic Contains function

func Contains[E comparable](s []E, v E) bool: Contains reports whether v is present in s.

We have to download this package and import it to our main.go

go get golang.org/x/exp/slices
import  "golang.org/x/exp/slices"

Example of using slices.Contains() function:

package main

import (
	"fmt"
	"golang.org/x/exp/slices"
)

func main() {
	names := []string{"Ana", "Bob", "Clair", "Daniel", "Fred", "Hush", "Timmy"}

	// some string to check
	nameCheck := "Bob"
	isPresent1 := slices.Contains(names, nameCheck)

	if isPresent1 {
		fmt.Println(nameCheck, "is in the names array")
	} else {
		fmt.Println(nameCheck, "is not in the names array")
	}

	scores := []float64{14.2, 26.5, 9.6, 36.4, 52.6}
	scoreCheck := 9.6

	isPresent2 := slices.Contains(scores, scoreCheck)
	if isPresent2 {
		fmt.Println(scoreCheck, "is in the scores array")
	} else {
		fmt.Println(scoreCheck, "is not in the scores array")
	}
}

Output

Bob is in the names array
9.6 is in the scores array

 

Summary

In this article, I have given few examples of checking if an array contains a given element. We can use a loop or built-in package slices.Contains() to do that.  If your slice is not too large, we can iterating over the entire array. For longer lists of data, you should consider using a map for storage, which has generally much better lookup performance than iterating over arrays.

 

References

https://go.dev/doc/tutorial/generics
https://pkg.go.dev/golang.org/x/exp/slices#Contains

 

Tuan Nguyen

Tuan Nguyen

He is proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment