Skip to content

Golang: Remove (Pop) First Element From Slice

Creating a queue in the Golang is easy and it can be written in some line of code. Pop from a slice can be done with a line of code like this:

package main

import "fmt"

func main() {
	queue := []string{"a", "b", "c", "d", "e", "f"}

	// inline version
	item, queue := queue[0], queue[1:]

	fmt.Println(item, queue)
}

Using a function to pop the first item + check length of slice:

package main

import "fmt"

func main() {
	queue := []string{"a", "b", "c", "d", "e", "f"}

	// function version
	item, queue := pop(queue)

	fmt.Println(item, queue)
}

func pop(q []string) (string, []string) {
	if len(q) == 0 {
		return "", []string{}
	} else if len(q) == 1 {
		return q[0], q[0:0]
	}
	return q[0], q[1:]
}
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *