How to check if an element is inside a slice in Golang
Overview
Slices are a built-in data type in Golang similar to arrays, except that a slice has no specified length. All elements within a slice must have the same type.
The code below shows how to declare a slice literal with the string type specification:
newSlice := []string{"a", "b", "c", "d"}
How to check if a slice contains an element
To check if a particular element is present in a slice object, we need to perform the following steps:
- Use a
forloop to iterate over each element in theslice. - Use the equality operator (
==) to check if the current element matches the element you want to find.
The code below demonstrates this process.
package mainimport ("fmt")func main(){// initialize a slice literalnewSlice := []string{"a", "b", "c", "d"}fmt.Println("The original slice is:", newSlice)// initialize the strings to search forsearchString := "c"// initialize a found flagfound := false// iterate over the slicefor i, v := range newSlice {// check if the strings matchif v == searchString {found = truefmt.Println("The slice contains", searchString, "at index", i)break}}// if string not foundif found == false {fmt.Println("The slice does not contain", searchString)}}
Explanation
In the code above:
-
In line , we import the
fmtpackage for printing. -
In line , we initialize a slice literal of the
stringtype callednewSlice. At the time of declaration,newSlicecontains values. -
Then, the code initializes the string to check the
slicefor in line . We also declare abooleanvariablefoundto serve as a flag that indicates whether or not thesearchStringis present innewSlice. -
The
forloop in line proceeds to iterate over each value innewSlice. -
The
ifstatement in line checks if the current element matchessearchString. If both strings match,foundis set totrue. The code prints the index at which the element was found and the loop is terminated. -
If the
slicedoes not containsearchString, the loop finishes its execution. However, the value offoundwould still befalse. Consequently, theifstatement in line checks whether or not the string was found.