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 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)}
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
lowerBounddefault value is0, and theupperBoundis the array’slength.
3. From slice
mySlice = sliceName[lowerBound:upperBound]
-
It returns a new slice containing slice elements in the
[lowerBound:upperBound)interval. -
The
lowerBounddefault value is0, and theupperBoundis the slice’ssize.
Code
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)}
Explanation
Earlier, we declared some slices. We will now initialize them.
- Line 13: We initialize
mySlice1using slice literal. - Line 14: We initialize
mySlice2from thearraywith the lower bound as 0 and the upper bound as 2. - Line 15: We initialize
mySlice3frommySlice1with 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.