How to remove the last element from a slice?

Go

Go Problem Overview


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.

Go Solutions


Solution 1 - Go

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

Solution 2 - Go

TL;DR:

myslice = myslice[:len(myslice) - 1]

This will fail if myslice is zero sized.

Longer answer:

Slices are data structures that point to an underlying array and operations like slicing a slice use the same underlying array.

That means that if you slice a slice, the new slice will still be pointing to the same data as the original slice.

By doing the above, the last element will still be in the array, but you won't be able to reference it anymore.

If you reslice the slice to its original length you'll be able to reference the last object

If you have a really big slice and you want to also prune the underlying array to save memory, you probably wanna use "copy" to create a new slice with a smaller underlying array and let the old big slice get garbage collected.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsourceyView Question on Stackoverflow
Solution 1 - GoSimon WhiteheadView Answer on Stackoverflow
Solution 2 - GoDallaRosaView Answer on Stackoverflow