OneBite.Dev - Coding blog in a bite size

count the number of occurrences of a specific element in an array in Go

Code snippet on how to count the number of occurrences of a specific element in an array in Go

  package main
  
  import "fmt"
  
  func main() {
    arr := []string{"alpha", "beta", "gamma", "gamma"}
    result := count("gamma", arr)
    fmt.Println("Number of gamma = ", result)
  }
  
  func count(val string, arr []string) int {
    counter := 0
    for _, value := range arr {
        if val == value {
            counter++
        }
    }
    return counter
  }

This code counts the number of occurrences of a specific element in an array in Go. The code begins by declaring an array of strings with four elements. A count() function is then declared and is passed a string value and the array as parameters. This function iterates through the array and increments the “counter” variable if the string value passed to the function is found in the array. Finally, the count() function returns the counter variable. The code then prints out the number of times the string value was found in the array.

go