[Golang] Make Slice Empty


After a slices contains some items and we want to empty the slice, how to write the syntax?

Use int array as example, the syntax is:

myArray = []int{}

See the following full example on Go Playground.

Run Code on Go Playground

package main

import (
      "fmt"
)

func printNumbers(numbers []int) {
      for _, number := range numbers {
              fmt.Println(number)
      }
}

func main() {
      // initialize int slice
      var numbers = []int{1, 2, 4, 5}
      printNumbers(numbers)

      // make slice empty
      numbers = []int{}
      printNumbers(numbers)
}

Tested on: Go Playground


References:

[1]