HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

How to remove the last element from a slice?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
lasthowfromslicetheremoveelement

Problem

I've seen people say just create a new slice by appending the old one

*slc = append(*slc[:item], *slc[item+1:]...)


but what if you want to remove the last element in the slice?

If you try to replace i (the last element) with i+1, it returns an out of bounds error since there is no i+1.

Solution

You can use len() to find the length and re-slice using the index before the last element:

if len(slice) > 0 {
    slice = slice[:len(slice)-1]
}


Click here to see it in the playground

Code Snippets

if len(slice) > 0 {
    slice = slice[:len(slice)-1]
}

Context

Stack Overflow Q#26172196, score: 150

Revisions (0)

No revisions yet.