Course: Learning GO

A collection of go basic fundamentals, syntax and concepts.

Table of contents

Lesson: Slices

2 - Slices

Unlike arrays, slices are only typed, and we don’t need to specify a length to them.

We can set and get just like with arrays.

  • To create an empty slice with non-zero length, use the built-in make() function.
  • You can also create a slice from an existing array or another slice using the slice operator [:]
var scores []string

scores:= make([]int, 3) // create a slice of type []int with length 3 and capacity 3

scores[0] = 1 // assign values to the slice elements

// Create slice from existing array
a := [5]int{1, 2, 3, 4, 5} // create an array of type [5]int
b := a[1:4] // create a slice of type []int from the array elements at index 1 to 3 (inclusive)

Slices are reference types,

which means that modifying a slice element will affect any other slices that share the same underlying array.

e := make([]int, 2) // create a slice of type []int with length 2 and capacity 2
e[0] = 10 // assign values to the slice elements
e[1] = 20

f := e // assign the slice e to another variable f
f[0] = 30 // modify the first element of f

fmt.Println(e) // print [30 20]
fmt.Println(f) // print [30 20]

To avoid this problem, you can use the built-in copy function, which copies the elements from one slice to another. For example:

g := make([]int, len(e)) // create a slice of type []int with the same length as e

copy(g, e) // copy the elements from e to g

g[0] = 40 // modify the first element of g

fmt.Println(e) // print [30 20]
fmt.Println(g) // print [40 20]

Operations on Slices

pop


pop, s1 := s[len(s)-1], s[:len(s)-1]
fmt.Println(s1) // [1 2 3 4]
fmt.Println(pop) // 5

shift

shift, s2 := s[0], s[1:]
fmt.Println(s2) // [2 3 4 5]
fmt.Println(shift) // 1