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]
- slice: This represents the slice you want to access.
- len(slice): This gives you the length (number of elements) of the slice.
- len(slice)-1: Since slice indices are 0-based, subtracting 1 from the length gives you the index of the last element.
- 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.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.