How to Create an Empty Slice in Golang

To create an empty slice in Golang, you can use the “empty pair of square brackets” or “make()” function.

Method 1: Using a literal syntax with empty brackets

Use a literal syntax with empty brackets to create an empty slice in Go. You need to use the := operator and an empty pair of square brackets [] followed by the data type of the elements that the slice will hold.

Example

package main

import (
 "fmt"
)

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

Output

[]

In this example, an empty slice of type string is created using the literal syntax with empty brackets. The slice will have a length of 0 and can be used to store elements of the specified type.

Method 2: Using the built-in make() function

You can also use the “make()” function to initialize an empty slice in Go.

Example

package main

import (
  "fmt"
)

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

Output

[]

In this example, an empty slice of type string is created using the make function with a length of 0.

1 thought on “How to Create an Empty Slice in Golang”

Leave a Comment