2

2 basic FIFO queue implementations

 3 years ago
source link: https://yourbasic.org/golang/implement-fifo-queue/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

2 basic FIFO queue implementations

yourbasic.org/golang
queue.jpg

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 com­mon tasks is a collection of handy code examples.

Share:             


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK