Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the last element from a slice?

Tags:

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.

like image 586
sourcey Avatar asked Oct 03 '14 01:10

sourcey


People also ask

How do you remove the last element using splice?

To remove the last n elements from an array, use arr. splice(-n) (note the "p" in "splice"). The return value will be a new array containing the removed elements.

How do you remove an element from a slice?

Removing an Element from a Slice Items need to be removed from a slice by slicing them out. To remove an element, you must slice out the items before that element, slice out the items after that element, then append these two new slices together without the element that you wanted to remove.

How do I remove the last element?

To remove last array element in JavaScript, use the pop() method. JavaScript array pop() method removes the last element from an array and returns that element.

How do you remove the last element of an array?

The pop() method removes (pops) the last element of an array. The pop() method changes the original array. The pop() method returns the removed element.


1 Answers

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

like image 54
Simon Whitehead Avatar answered Sep 29 '22 10:09

Simon Whitehead