OneBite.Dev - Coding blog in a bite size

count array's length in Go

Code snippet on how to count array's length in Go

package main 
 
import "fmt"
 
func main() {
    // Declare an array of 5 strings
    fruits := [5]string{"Apple", "Grape", "Mango", "Banana", "Strawberry"}
 
    // Get the length of the array
    length := len(fruits)
 
    // Print the length
    fmt.Println("Length of fruits array:", length)
}

We start by creating a package called ‘main’, which is a collection of functions and other Go code used to build an executable program. Then, we import a package called ‘fmt’, which is used to print output to the console. In the main function, we declare an array with 5 string elements. Then, we use the built in ‘len()’ function to get the length of the array. Lastly, we use the ‘fmt’ package to print the length of the array.

go