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.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
