Skip to content

Go: Remove the Last Element From a Slice

Get the index of the last item in Golang by using len() method:

len(mySlice)-1    // index of last item

The slice index starts from 0 and you can access the last element in the slice by:

mySlice[len(mySlice)-1]

A simple example of getting the last item:

package main

import "fmt"

func main() {
	userList := []string{"Morteza", "Mona", "Jack"}

	// get the last item in the slice
	lastUser := userList[len(userList)-1]

	fmt.Println(lastUser)
}

How to remove the last element from a slice:

package main

import "fmt"

func main() {
	userList := []string{"Morteza", "Mona", "Jack"}

	// remove the last element
	userList = userList[:len(userList)-1]

	fmt.Println(userList)
}

Leave a Reply

Your email address will not be published. Required fields are marked *