The simplest way to implement the queue data structure in Golang is to use a slice. Since a queue follows a FIFO (First-In-First-Out) structure, the dequeue and enqueue operations can be performed as follows:
append
function to enqueue.The diagram below illustrates these two operations:
The following code snippet implements a basic queue using a slice. Note how enqueuing and dequeuing occur at opposite ends of the slice.
package mainimport "fmt"func enqueue(queue[] int, element int) []int {queue = append(queue, element); // Simply append to enqueue.fmt.Println("Enqueued:", element);return queue}func dequeue(queue[] int) ([]int) {if len(queue) == 0 {fmt.Println("Cannot dequeue from an empty queue")return queue}element := queue[0]; // The first element is the one to be dequeued.fmt.Println("Dequeued:", element)return queue[1:]; // Slice off the element once it is dequeued.}func main() {var queue[] int; // Make a queue of ints.queue = enqueue(queue, 10);queue = enqueue(queue, 20);queue = enqueue(queue, 30);fmt.Println("Queue:", queue);queue = dequeue(queue);fmt.Println("Queue:", queue);queue = enqueue(queue, 40);fmt.Println("Queue:", queue);}
Warning(memory-leaks): In the dequeue function above, the memory allocated for the first element in the array is never returned.
We can use dynamic data structure(linked list) in order to avoid memory leaks. The sample code is given below:
package mainimport "container/list"import "fmt"func main() {// new linked listqueue := list.New()// Simply append to enqueue.queue.PushBack(10)queue.PushBack(20)queue.PushBack(30)// Dequeuefront:=queue.Front()fmt.Println(front.Value)// This will remove the allocated memory and avoid memory leaksqueue.Remove(front)}
Free Resources