0
0
GoHow-ToBeginner · 3 min read

How to Find Length of Slice in Go: Simple Guide

In Go, you find the length of a slice using the len() function. Just pass your slice to len(), and it returns the number of elements in that slice.
📐

Syntax

The syntax to find the length of a slice is simple:

  • len(slice): Returns the number of elements in the slice.

Here, slice is your slice variable.

go
length := len(slice)
💻

Example

This example shows how to create a slice and find its length using len(). It prints the length to the console.

go
package main

import "fmt"

func main() {
    numbers := []int{10, 20, 30, 40, 50}
    length := len(numbers)
    fmt.Println("Length of slice:", length)
}
Output
Length of slice: 5
⚠️

Common Pitfalls

Some common mistakes when finding slice length:

  • Using len() on a nil slice returns 0, which is correct but sometimes unexpected.
  • Confusing slice length with capacity. len() gives length, not capacity.
  • Trying to get length of an array pointer instead of the array or slice itself.
go
package main

import "fmt"

func main() {
    var s []int // nil slice
    fmt.Println("Length of nil slice:", len(s)) // prints 0

    arr := [3]int{1, 2, 3}
    // fmt.Println(len(&arr)) // wrong: cannot use pointer with len()
    fmt.Println(len(arr)) // correct: prints 3
}
Output
Length of nil slice: 0 3
📊

Quick Reference

Remember these tips when working with slice length:

  • len(slice) returns the number of elements.
  • Length is always ≥ 0, even for nil slices.
  • Capacity (cap(slice)) is different from length.

Key Takeaways

Use len(slice) to get the number of elements in a slice.
len() returns 0 for nil slices without error.
Length and capacity of a slice are different concepts.
Do not use len() on pointers to arrays or slices.
len() is a built-in, fast, and safe way to get slice length.