What is the empty or zero value for a slice in Go or Golang?

Published September 5, 2022

The empty or zero value of a slice in go or golang is nil. These slices have a capacity and a length of 0.

TL;DR

package main

import "fmt"

func main() {
    // declare an int slice
    var mySlice []int

    // check if the mySlice zero value is
    // `nil` using an if conditional statement
    if mySlice == nil {
        fmt.Println("The zero value is nil") // The zero value is nil ✅ This will be printed upon execution.

        // check the capacity and the length of the `mySlice` slice
        fmt.Println(cap(mySlice), len(mySlice)) // 0 0 ✅
    }
}

For example, First, let's declare an int slice like this,

package main

func main(){
    // declare an int slice
    var mySlice []int
}

Now to see if the initial or the zero value of the mySlice slice, let's use a simple if conditional check to see if the slice is equal to the value of nil.

It can be done like this,

package main

import "fmt"

func main(){
    // declare an int slice
    var mySlice []int

    // check if the mySlice zero value is
    // `nil` using an if conditional statement
    if mySlice == nil {
        fmt.Println("The zero value is nil") // The zero value is nil ✅ This will be printed upon execution.
    }
}

As you can see that the if condition has become true which, proves that the zero value of the mySlice slice is nil.

Now let's also print the capacity and the length of the mySlice slice using the cap() and the len() method respectively.

It can be done like this,

package main

import "fmt"

func main() {
    // declare an int slice
    var mySlice []int

    // check if the mySlice zero value is
    // `nil` using an if conditional statement
    if mySlice == nil {
        fmt.Println("The zero value is nil") // The zero value is nil ✅ This will be printed upon execution.

        // check the capacity and the length of the `mySlice` slice
        fmt.Println(cap(mySlice), len(mySlice)) // 0 0 ✅
    }
}

As you can see that the zero value of the slice is nil and the capacity and length of the slice are 0.

See the above code live in The Go Playground.

That's all 😃.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter