0
0
GoHow-ToBeginner · 3 min read

How to Check if Slice Contains Element in Go

In Go, you check if a slice contains an element by looping through the slice and comparing each item to the target element. If a match is found, you can return true; otherwise, false. This manual check is common because Go does not have a built-in function for this.
📐

Syntax

To check if a slice contains an element, you typically use a for loop to go through each item and compare it with the element you want to find.

The pattern looks like this:

  • for _, item := range slice: loops over each element in the slice.
  • if item == target: checks if the current item matches the element you want.
  • return true: returns true if found.
  • return false: returns false if the loop finishes without a match.
go
func contains(slice []string, element string) bool {
    for _, item := range slice {
        if item == element {
            return true
        }
    }
    return false
}
💻

Example

This example shows how to check if a slice of strings contains a specific string. It prints true if the element is found, otherwise false.

go
package main

import (
    "fmt"
)

func contains(slice []string, element string) bool {
    for _, item := range slice {
        if item == element {
            return true
        }
    }
    return false
}

func main() {
    fruits := []string{"apple", "banana", "cherry"}
    fmt.Println(contains(fruits, "banana")) // true
    fmt.Println(contains(fruits, "grape"))  // false
}
Output
true false
⚠️

Common Pitfalls

One common mistake is trying to use built-in functions like contains directly on slices, but Go does not provide this. You must write your own loop or helper function.

Another pitfall is comparing elements of different types or forgetting to handle empty slices, which can cause unexpected results.

go
package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3}
    // Wrong: no built-in contains for slices
    // fmt.Println(contains(numbers, 2)) // Error: undefined: contains

    // Right: write your own function
    fmt.Println(contains(numbers, 2)) // true
}

func contains(slice []int, element int) bool {
    for _, item := range slice {
        if item == element {
            return true
        }
    }
    return false
}
Output
true
📊

Quick Reference

  • Use a for loop with range to iterate over slice elements.
  • Compare each element with the target using ==.
  • Return true immediately if found, else false after the loop.
  • Write helper functions for reuse.

Key Takeaways

Go does not have a built-in function to check if a slice contains an element, so you must loop manually.
Use a for loop with range to compare each element to the target value.
Return true as soon as you find the element to avoid unnecessary checks.
Write reusable helper functions to keep your code clean and readable.
Always ensure the element type matches the slice element type to avoid errors.