How to get the last element of a slices in golang?

Hi 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

  1. the len() method to get length of slice
  2. subtract 1 to get last index of slice because index start from 0
  3. 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

Try it yourself

All the best 👍