Start learning free

LESSON 107 OF 671 · ARRAYS I

Slice Length in Go

Lesson

We can get the length of a slice using the len() function:

ourArray := []int{50, 40, 30}

// Printing the length:
fmt.Println(len(ourArray)) // Output: 3

// Changing the slice:
ourArray = ourArray[:len(ourArray)-1]

// Printing the new length:
fmt.Println(len(ourArray)) // Output: 2

Using the length

We can use the length to access items from the end of a slice.

Because slices are 0-indexed, the index of the last item is length - 1:

ourArray := []int{50, 40, 30}

size := len(ourArray)

// Printing the last item:
fmt.Println(ourArray[size - 1]) // Output: 30

// Printing the second to last item:
fmt.Println(ourArray[size - 2]) // Output: 40

Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check