How to get the last element of a slice in Golang
In this tutorial, we will learn how to get the last element of a slice in Golang.
In Go, the elements in the silce can be accessed by using its index number, where the first element index is [0]
, the second element index is [2]
, etc.
Getting the last element
To access the last element of a slice, we can use the slice expression []
by passing len(slice)-1
in Go.
Here is an example, that gets the last element 45
from the prices slice:
prices := []int{15,25,35,45}
lastElement := prices[len(prices)-1]
fmt.Println(lastElement)
Output:
45