Empty Slice vs. Nil Slice in Golang


In this article, we will see the differences and similarities that are there between a slice that is declared as an empty and a nil slice.

Slices in Golang are used to store a sequence of elements. Slices can be expanded at any time and they are declared in the same way as an array, but without their capacity defined.

Nil Slice

A nil slice is a slice in which while declaring, we simply define the name and the data type and not make use of the built-in make function.

A nil slice is a slice that has nil as its zero value and the length and capacity of the slice would also be 0 at the beginning and it also doesn't have an underlying array.

Example 1

Consider the code shown below.

package main

import (
   "fmt"
)

func main() {
   var sl []string
   fmt.Println(sl)
   fmt.Println(len(sl))
   fmt.Println(cap(sl))

   sl = append(sl, "India", "Japan")
   fmt.Println(sl)
   fmt.Println(len(sl))
   fmt.Println(cap(sl))
}

In the above code, we declared a nil slice and then printed the length and capacity of that slice.

Output

If we run the command go run main.go on the above code then we will get the following output in the terminal.

[]
0
0
[India Japan]
2
2

Empty Slice

An empty slice is a slice that is declared by using the built-in make function and it doesn't have nil as its zero value.

Example 2

Consider the code shown below.

package main

import (
   "fmt"
)

func main() {
   sl := make([]string, 0)
   fmt.Println(sl)
   fmt.Println(sl == nil)
   fmt.Println(len(sl))
   fmt.Println(cap(sl))

   sl = append(sl, "India", "Japan")
   fmt.Println(sl)
   fmt.Println(len(sl))
   fmt.Println(cap(sl))
}

Output

If we run the command go run main.go on the above code then we will get the following output in the terminal.

[]
false
0
0
[India Japan]
2
2

Updated on: 01-Nov-2021

811 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements