How to initialize a slice in Golang

In Golang, a slice is an abstraction over an array. Unlike an array, we can resize a slice at run time.

In this shot, we’ll learn to initialize a slice in Golang. Let’s declare some slices first:

package main
import "fmt"
func main() {
var array = []string{"Edpresso", "Educative", "Shots"}
// slice declaration
var mySlice1 []int
var mySlice2 []string
var mySlice3 []int
// print slice on console
fmt.Println(array)
fmt.Println(mySlice1)
fmt.Println(mySlice2)
fmt.Println(mySlice3)
}

Explanation

  • Line 6: We declare an array.
  • Line 7-10: We declare three slices of the int, string, and int type, respectively.
  • Line 13-16: We output them on the console.

For now, all the slices are empty. We will initialize them later in the shot.

Slice initialization

We can initialize a slice in the following ways.

1. Using slice literal

mySlice = []dataType{elements}
  • When using a slice literal, we should not specify the slice’s size within the square brackets.

2. From array

mySlice = arrayName[lowerBound:upperBound] 
  • It returns a new slice containing array elements in the [lowerBound:upperBound) interval.

  • The lowerBound default value is 0, and the upperBound is the array’s length.

3. From slice

mySlice = sliceName[lowerBound:upperBound] 
  • It returns a new slice containing slice elements in the [lowerBound:upperBound) interval.

  • The lowerBound default value is 0, and the upperBound is the slice’s size.

Code

In the code snippet below, we initialize the slice using the ways mentioned above.

package main
import "fmt"
func main() {
var array = []string{"Edpresso", "Educative", "Shots"}
// slice declaration
var mySlice1 []int
var mySlice2 []string
var mySlice3 []int
// slice initialization
mySlice1 = []int{1, 2, 3, 4}
mySlice2 = array[0:2]
mySlice3 = mySlice1[0:3]
// print slice on console
fmt.Println(mySlice1)
fmt.Println(mySlice2)
fmt.Println(mySlice3)
}

Explanation

Earlier, we declared some slices. We will now initialize them.

  • Line 13: We initialize mySlice1 using slice literal.
  • Line 14: We initialize mySlice2 from the array with the lower bound as 0 and the upper bound as 2.
  • Line 15: We initialize mySlice3 from mySlice1 with the lower bound as 0 and the upper bound as 3.
  • We can now see that slices are initialized with some values in the console.

Free Resources