How to count the occurences of a character in a Go string

The simplest way to count the number of occurrences of a character in a string in Go is by using the strings.Count method. For example, to count how many times a appears in ‘Mary had a little lamb’, use the following code snippet:

package main

import (

func main() {
	str := "Mary had a little lamb"
	fmt.Println(strings.Count(str, "a")) // 4
  <a class="code-link" target="_blank" rel="noreferrer" href="">
    Run code snippet on the Go playground

Thanks for reading, and happy coding!