Check if Slice contains Specific Element

To check if slice contains a specific element in Go, iterate over elements of slice using a for loop, and check for the equality of values using equal to operator. If there is a match, we may stop the search and conclude that the element in present in the slice.

Example

In the following program, we take a slice of integers in slice1. We check if the element 40 is present in this slice.

example.go

package main

import "fmt"

func main() {
	slice1 := []int{10, 20, 30, 40, 50}
	var element int = 40

	var result bool = false
	for _, x := range slice1 {
		if x == element {
			result = true
			break
		}
	}

	if result {
		fmt.Print("Element is present in the slice.")
	} else {
		fmt.Print("Element is not present in the slice.")
	}
}

Output

Element is present in the slice.
ADVERTISEMENT

Conclusion

In this Golang Tutorial, we learned how to find if a slice contains a given element, with the help of example programs.