Start learning free

LESSON 114 OF 671 · ARRAYS I

Slicing a Slice in Go

Lesson

TL ; DR:

s[i:j] is a slice with the items from index i up to, not including, j. It shares those items with s.


letters := []string{"a", "b", "c", "d", "e"}

middle := letters[1:4]
fmt.Println(middle)    // [b c d]

fmt.Println(letters)   // [a b c d e]


Full lesson:

Sometimes you need only part of a slice, like the first few items. Slicing gives you that part.

Write the start index and the end index in brackets, with a colon between them. The item at the end index is not included. So letters[1:4] has the items at 1, 2 and 3.

You've seen this before. In Remove Last Item, s[:len(s)-1] dropped the last item.

Leave out the start to begin at index 0. Leave out the end to go to the very end:

fmt.Println(letters[:2])   // [a b]
fmt.Println(letters[3:])   // [d e]

Slicing doesn't change letters. It still has five items.

But a Go slice copies nothing. It shares the same items, so changing middle[0] changes letters[1] too. The next lesson, Slices vs Arrays, shows this in detail.


Your task

runners holds a race's runners, in the order they finished.

Put the first three in a new slice named podium. Put everyone else, from index 3 to the end, in one named rest.

The code below prints both, then the length of runners.

Expected output:

Ana Ben Cleo
Dan Eve
5
STEP 1 OF 2
    Ctrl + Enter to check