How to get the last element of a slice?
What is the Go way for extracting the last element of a slice?
var slice []int
slice = append(slice, 2)
slice = append(slice, 7)
slice[len(slice)-1:][0] // Retrieves the last element
The solution above works, but seems awkward.
Solution 1:
For just reading the last element of a slice:
sl[len(sl)-1]
For removing it:
sl = sl[:len(sl)-1]
See this page about slice tricks
Solution 2:
You can use the len(arr)
function, although it will return the length of the slice starting from 1, and as Go arrays/slices start from index 0 the last element is effectively len(arr)-1
Example:
arr := []int{1,2,3,4,5,6} // 6 elements, last element at index 5
fmt.Println(len(arr)) // 6
fmt.Println(len(arr)-1) // 5
fmt.Println(arr[len(arr)-1]) // 6 <- element at index 5 (last element)