Golang Code

Find the Length of an Array/Slice

· 86 words · 1 minute read #array #find #fmt #len #length

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.

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.

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!