How to remove the last element from a slice?
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
TL;DR:
myslice = myslice[:len(myslice) - 1]
By the way, this will fail if "myslice" is zero sized.
Longer answer:
myslice = myslice[:len(myslice) - 1]
This will fail if "myslice" is zero sized.
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.
Edit
Clarification: If you reslice the slice to its original length you'll be able to reference the last object
/Edit
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.