2 basic FIFO queue implementations
yourbasic.org/golang
A simple way to implement a temporary queue data structure 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.
var queue []string
queue = append(queue, "Hello ") // Enqueue
queue = append(queue, "world!")
for len(queue) > 0 {
fmt.Print(queue[0]) // First element
queue = queue[1:] // Dequeue
}
Hello world!
Watch out for memory leaks
You may want to remove the first element before dequeuing.
// Dequeue
queue[0] = "" // Erase element (write zero value)
queue = queue[1:]
Warning: 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.
queue := list.New()
queue.PushBack("Hello ") // Enqueue
queue.PushBack("world!")
for queue.Len() > 0 {
e := queue.Front() // First element
fmt.Print(e.Value)
queue.Remove(e) // Dequeue
}
Hello world!
More code examples
Go blueprints: code for common tasks is a collection of handy code examples.