To get the last element in an array in Go, you can use array indexing similar to other languages.
In this example,
numbers
with some elements.numbers[len(numbers)-1]
and store it in the variable lastNumber
.lastNumber
.package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5}
lastNumber := numbers[len(numbers)-1]
fmt.Println("Last number is:", lastNumber)
}
Last number is: 5
In this example,
fruits
with some elements.fruits[len(fruits)-1]
and store it in the variable lastFruit
.lastFruit
.package main
import "fmt"
func main() {
fruits := []string{"apple", "banana", "cherry"}
lastFruit := fruits[len(fruits)-1]
fmt.Println("Last fruit is:", lastFruit)
}
Last fruit is: cherry
In this tutorial, we learned How to get Last Element in Array in Go language with well detailed examples.