[Golang] Check If Item in Slice or Array


Question

How to check if an item is in a slice or array in Go?

Solution

There are many methods to do this [1]. My approach is to create a map [2] type and save the items of slice/array in the map, and then check if the item is in the map or not.

The following is an example of above approach.

Run Code on Go Playground

package main

import (
      "fmt"
)

func main() {
      // initialize a slice of int
      slice := []int{2, 3, 5, 7, 11, 13}

      // save the items of slice in map
      m := make(map[int]bool)
      for i := 0; i < len(slice); i++ {
              m[slice[i]] = true
      }

      // check if 5 is in slice by checking map
      if _, ok := m[5]; ok {
              fmt.Println("5 is in slice")
      } else {
              fmt.Println("5 is not in slice")
      }

      // check if 6 is in slice by checking map
      if _, ok := m[6]; ok {
              fmt.Println("6 is in slice")
      } else {
              fmt.Println("6 is not in slice")
      }
}

To see real-world application, see reference [3]. The prime numbers are returned in a slice. Then the prime numbers are saved in the map, and we can check if a number is prime or not by checking if the number is in the map.

Tested on: Go Playground


References:

[1]
[2]Go maps in action - The Go Blog
[3][Golang] Goldbach's conjecture
[4]📣 [Data Structures with Go]: Data Structures and Algorithms Example: Array, Binary Tree, Linked List, Sort (Quick, Merge), Stack, Queue (my Midterm & Final study notes for Data Structure course) (Feel Free to Contribute) : golang