OneBite.Dev - Coding blog in a bite size

get the last element of array in Go

Code snippet on how to get the last element of array in Go

  l := len(arr) - 1
  lastElement := arr[l]

This code will get the last element of an array in Go. First we define a new variable “l” and assign it to the length of the array (“arr”) minus one. Since arrays are zero-indexed meaning that the last element is one less than the total number of elements, we subtract one to get the position of the last element. Then, we define a new variable “lastElement” and assign it to the array at the position given by “l” which has been calculated to be the last element. This code executes the task of getting the last element of an array.

go