How to Get the Last Element of a Slice

To get the last element of a slice in Go, you can use the slice[len(slice)-1] expression as long as the slice is not empty. The length of a slice can be obtained using the built-in len() function.

Syntax

slice[len(slice)-1]
  1. slice: This represents the slice you want to access.
  2. len(slice): This gives you the length (number of elements) of the slice.
  3. len(slice)-1: Since slice indices are 0-based, subtracting 1 from the length gives you the index of the last element.
  4. slice[len(slice)-1]: This expression is used to access the last element of the slice.

Example

package main

import (
  "fmt"
)

func main() {
  mainSlice := []int{11, 21, 19, 46, 17}

  if len(mainSlice) == 0 {
    fmt.Println("The slice is empty.")
  } else {
    lastElement := mainSlice[len(mainSlice)-1]
    fmt.Println("The last element of the slice is:", lastElement)
  }
}

Output

The last element of the slice is: 17

In this code example, we first checked if the slice was empty by comparing its length to 0.

Check whether the slice is empty before using this expression, as trying to access a non-existent index (e.g., when the slice is empty) will cause a runtime panic.

If the slice is not empty, we use the len() function to find the index of the last slice using the (len(mainSlice) – 1) expression and access the last element consequently.

That’s it.

Leave a Comment