HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
succinctlyhowfromslicetheremoveelementfirst

Problem

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.

Solution

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://go.dev/wiki/SliceTricks

Code Snippets

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

Context

Stack Overflow Q#23531891, score: 305

Revisions (0)

No revisions yet.