Go: Implement a FIFO queue

A simple way to implement a temporary queue in Go is to use a slice:

  • to enqueue you use the built-in append function, and
  • to dequeue you slice off the first element.
// Create
var queue []string

// Enqueue
queue = append(queue, "Hello ")
queue = append(queue, "world!")

for len(queue) > 0 {
	// Print first
	fmt.Print(queue[0])

	// Dequeue
	queue = queue[1:]
}
// Output: Hello world!

Watch out for memory leaks

You may want to remove the first element before dequeuing:

// Dequeue
queue[0] = "" // to avoid memory leak
queue = queue[1:]

Also, note that the memory allocated for the array is never returned. For a long-living queue you should probably use a dynamic data structure, such as a linked list.

Linked list

The container/list package implements a doubly linked list which can be used as a queue.

// Create
queue := list.New()

// Enqueue
queue.PushBack("Hello ")
queue.PushBack("world!")

for queue.Len() > 0 {
	// Print first
	e := queue.Front()
	fmt.Print(e.Value)

	// Dequeue
	queue.Remove(e)
}
// Output: Hello world!

Comments