Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator

# How to remove the last item from a slice in Golang

Yashaswini Kamatham

### Overview

In this shot, we will learn to remove the last item from a slice in Golang.

Slice is a dynamically sized array in Golang:

• It can grow and shrink when we add or remove elements from it.
• Can only contain similar types of elements.
• Declaring a slice is the same as an array but without a size.

Example:

_n_ := []int{1, 2, 3, 4, 5, 6, 7}

Removing last element from a slice

### Example

We will remove the last item from a given slice:

{1,2,3,4,5,6,7}

The last item is $7$ here.

We will follow the below approach to remove the last item:

• Calculate the length of the slice
• Re-slice the original slice to last before element

### Code

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)

}

### Explanation

• Line 9: We have the main() function that is the start of the program execution.
• Line 12: We declare and initialize slice n.
• Line 15: We check for a non-empty slice, otherwise if we try to reslice an empty slice it will throw an error.
• Line 18: We reslice the original slice to the second last element. We find out the second last element by subtracting 1 from the length of the slice.
• Line 22: We display the slice after removing the last element.

RELATED TAGS

golang
communitycreator

CONTRIBUTOR

Yashaswini Kamatham
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time

Copyright Â©2022 Educative, Inc. All rights reserved.