In this shot, we will learn to remove the last item from a slice in Golang.
Slice is a dynamically sized array in Golang:
Example:
_n_ := []int{1, 2, 3, 4, 5, 6, 7}
We will remove the last item from a given slice:
{1,2,3,4,5,6,7}
The last item is here.
We will follow the below approach to remove the last item:
package main //import format package import( "fmt" ) //main program func main(){ //Declare slice n := []int{1, 2, 3, 4, 5, 6, 7} //check if slice is not empty if len(n) > 0 { //Re-slice to last before element n = n[:len(n)-1] } //display slice where last element is removed fmt.Println(n) }
main()
function that is the start of the program execution.n
.1
from the length of the slice.RELATED TAGS
CONTRIBUTOR
View all Courses