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 packageimport("fmt")//main programfunc main(){//Declare slicen := []int{1, 2, 3, 4, 5, 6, 7}//check if slice is not emptyif len(n) > 0 {//Re-slice to last before elementn = n[:len(n)-1]}//display slice where last element is removedfmt.Println(n)}
main()
function that is the start of the program execution.n
.1
from the length of the slice.