How to remove the last item from a slice?

I saw people say that just create a new fragment by adding the old

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

but what if you want to delete the last item in a slice?

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

+7
go
source share
2 answers

You can use len() to find the length and the repeated fragment using the index before the last element:

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

Click here to see it on the playground.

+12
source share

TL; DR:

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

By the way, this will happen if "myslice" is zero size.

Longer answer:

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

This will happen if "myslice" is zero size.

Slopes are data structures that point to a base array, and operations, such as slice slice, use the same base array.

This means that if you slice a slice, the new slice will still point to the same data as the original slice.

Performing the above, the last element will still be in the array, but you can no longer reference it.

Edit

Explanation: If you cut the slice to its original length, you can refer to the last object

/ Edit

If you have a really large fragment, and you also want to trim the base array to save memory, you probably want to use a โ€œcopyโ€ to create a new slice with a smaller base array and allow the old large fragment to collect garbage.

0
source share

All Articles