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 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts