How to get the last element of a slices in golang?
October 30, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
To get the last element of a slices, use len(slice) - 1
it will return last element of slice.
Here, we are using
- the
len()
method to get length of slice - subtract
1
to get last index of slice because index start from0
- Accessing element by it’s key which we got from
len(slice) - 1
Let’s start
package main
import "fmt"
func main() {
slice := []int{1,2,3,4,5,6}
fmt.Println("Last Element", slice[len(slice) - 1])
}
In the above program, we are trying to access value from their key, let’s see the output.
Output:
Last Element 6
All the best 👍