25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started →
Checking if a Slice Contains an Element in Go
Code Snippet

Checking if a Slice Contains an Element in Go

go

Checking whether a slice contains a specific element is a common operation in Go. This snippet demonstrates a straightforward approach using a loop-based search function.

The function iterates through each element in the slice and compares it with the target value. As soon as a match is found, the function returns true. If the loop completes without finding a match, the function returns false. This approach is simple, readable, and works with any comparable type.

For Go 1.21 and later, the standard library provides slices.Contains() which offers the same functionality with a cleaner syntax. The manual loop approach shown here is useful for understanding the fundamental logic and remains compatible with earlier Go versions. Choose the built-in function for modern code, but knowing how to implement this yourself is valuable for custom matching logic.

Further Reading: