ChatGPT解决这个技术问题 Extra ChatGPT

How to remove the last element from a slice?

go

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.


S
Simon Whitehead

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


See I would have though it would have been slice[:1], why is that wrong? :(
I would have expected slice[:1] to remove the last element
@OlegzandrDenman The documentation discusses low and high bounds though. slice[:1] wouldn't be "1 index away from the end" ... its 1 as the high bound of a range.
May I mention that the use of <kbd> tags for a Go Playground link is rather elegant
Note. This could produce so much garbage.
g
ggorlen

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.


关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now