golang slices are subsets. A slice can be a subset of an array, list or string. You can take multiple slices out of a string, each as a new variable.

A slice is never longer than then the original variable. This makes sense, if you take a slice of a pizza you don’t suddenly have two pizzas. In programming it’s similar.

Download PDF

Slices in golang

Example

The golang code will take a slice out of a list of numbers.

Start by creating a list of numbers (myset). Then take a slice by specifying the lower and upper bounds. In programming languages the lower bounds is zero (arrays start at 0).

1
2
3
4
5
6
7
8
9
10
11
12
package main

import "fmt"

func main() {
/* create a set/list of numbers */
myset := []int{0,1,2,3,4,5,6,7,8}

/* take slice */
s := myset[0:4]
fmt.Println(s)
}

The above program takes a slice and outputs it.

1
[0 1 2 3]

String slicing

golang strings can be sliced too. The resulting slice will then also be a string, but of smaller size.

When slicing, remember that the index 0 is the first character of the string. The last character is the numbers of characters minus 1.

1
2
3
4
5
6
7
8
9
10
11
12
package main

import "fmt"

func main() {
/* define a string */
mystring := "Go programming"

/* take slice */
s := mystring[0:2]
fmt.Println(s)
}

Video

Video tutorial below:

Exercises

  1. Take the string ‘hello world’ and slice it in two.
  2. Can you take a slice of a slice?