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 mainimport "fmt"func main() {var array = []string{"Edpresso", "Educative", "Shots"}// slice declarationvar mySlice1 []intvar mySlice2 []stringvar mySlice3 []int// print slice on consolefmt.Println(array)fmt.Println(mySlice1)fmt.Println(mySlice2)fmt.Println(mySlice3)}
For now, all the slices are empty. We will initialize them later in the shot.
We can initialize a slice in the following ways.
mySlice = []dataType{elements}
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
.
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
.
In the code snippet below, we initialize the slice using the ways mentioned above.
package mainimport "fmt"func main() {var array = []string{"Edpresso", "Educative", "Shots"}// slice declarationvar mySlice1 []intvar mySlice2 []stringvar mySlice3 []int// slice initializationmySlice1 = []int{1, 2, 3, 4}mySlice2 = array[0:2]mySlice3 = mySlice1[0:3]// print slice on consolefmt.Println(mySlice1)fmt.Println(mySlice2)fmt.Println(mySlice3)}
Earlier, we declared some slices. We will now initialize them.
mySlice1
using slice literal.mySlice2
from the array
with the lower bound as 0 and the upper bound as 2.mySlice3
from mySlice1
with the lower bound as 0 and the upper bound as 3.