Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I (succinctly) remove the first element from a slice in Go?

Tags:

go

queue

I've built a simple queue in Go. It uses an internal slice to keep track of its elements. Elements are pushed onto the queue by appending to the slice. I'd like to implement .Pop() by removing the first element in elements.

In many other languages, "popping" the first element of a list is a one-liner, which leads me to believe my implementation below is sloppy and verbose. Is there a better way?

type Queue struct {     elements []interface{} }  func (queue *Queue) Push(element interface{}) {     queue.elements = append(queue.elements, element) }  func (queue *Queue) Pop() interface{} {     element := queue.elements[0]     if len(queue.elements) > 1 {         queue.elements = queue.elements[1:]     } else {         queue.elements = make([]interface{}, 0)     }     return element } 

Please note that I wish for the Queue to panic if len(queue.elements) == 0. It's not an oversight that I don't check the bounds.

like image 933
modocache Avatar asked May 08 '14 02:05

modocache


People also ask

How do you remove the first element of a slice in Golang?

Remove first element of slice (shift, pop(0))

How do you delete a slice element?

To remove the first element, call remove(s, 0), to remove the second, call remove(s, 1), and so on and so forth. Hm, not really. This: s[i] = s[len(s)-1] definitely copies the last element to the element at index i . Then, return s[:len(s)-1] returns the slice without the last element.

How do you remove the first element from a queue?

To take an element from a Java Queue you can call either its poll() or remove() method. The poll() and remove() both removes the first element in the Queue.

How do you clear a slice in Go?

Setting the slice to nil is the best way to clear a slice. nil slices in go are perfectly well behaved and setting the slice to nil will release the underlying memory to the garbage collector. Note that slices can easily be aliased so that two slices point to the same underlying memory.


1 Answers

Did you try these?

Pop from queue

x, a = a[0], a[1:] 

Pop from stack

x, a = a[len(a)-1], a[:len(a)-1] 

Push

a = append(a, x) 

From: https://code.google.com/p/go-wiki/wiki/SliceTricks

like image 84
Everton Avatar answered Sep 25 '22 02:09

Everton