Create an Empty Slice in Go

Create an Empty Slice in Go

Jay Singh Feb-23, 2022 Go Go Slice
  1. Initialize an Empty Slice in Go
  2. Use make() to Create an Empty Slice in Go

This article will discuss implementing empty slices in Go.

Initialize an Empty Slice in Go

An empty slice has a reference to an empty array. It has zero length and capacity and points to a zero-length underlying array.

We can initialize an empty slice in Go using the code below.

package main

import "fmt"

func main() {
    b := []string{}
    fmt.Println(b == nil)
}

Output:

false

Use make() to Create an Empty Slice in Go

The make() function can also generate an empty slice.

Below are some examples of code using make().

Example 1:

package main

import "fmt"

func main() {
    c := make([]string, 0)
    fmt.Println(c == nil)
}

Output:

false

Example 2:

package main

import "fmt"

func main() {
    // Creating an array of size 6
    // and slice this array  till 3
    // and return the reference of the slice
    // Using make() function
    var sliceA = make([]int, 3, 6)
    fmt.Printf("SliceA = %v, \nlength = %d, \ncapacity = %d\n",
        sliceA, len(sliceA), cap(sliceA))

    // Creating another array of size 6
    // and return the reference of the slice
    // Using make() function
    var sliceB = make([]int, 6)
    fmt.Printf("SliceB = %v, \nlength = %d, \ncapacity = %d\n",
        sliceB, len(sliceB), cap(sliceB))
}

Output:

SliceA = [0 0 0], 
length = 3, 
capacity = 6
SliceB = [0 0 0 0 0 0], 
length = 6, 
capacity = 6

Related Article - Go Slice

  • Delete an Element From a Slice in Golang
  • Golang Copy Slice
  • GoLang Sort Slice of Structs
  • Difference Between []String and ...String in Go
  • Check if a Slice Contains an Element in Golang