Find the Length of an Array/Slice

· 102 words · 1 minute read

With Go, you can find the length of an array (or more accurately a slice) by using the internal len() function. Our example shows us creating a slice and then printing out it’s length, then adding an extra item and printing the length again.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import "fmt"

func main() {

    // Create an exmaple array
    array := []int{1, 2, 3, 4, 5}

    // Print number of items
    fmt.Println("First Length:", len(array))

    // Add an item and print again
    array = append(array, 6)
    fmt.Println("Second Length:", len(array))
}

Get the length of a slice

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!