Open In App

Queue in Go Language

Last Updated : 29 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO)

Now if you are familiar with other programming languages like C++, Java, and Python then there are inbuilt queue libraries that can be used for the implementation of queues, but such is not the case in the case of Golang. Even if you are not familiar with those then just know that Golang does not provide an inbuilt queue structure.

How to implement Queue in Go Language?

There are many ways to implement queues in Golang using other Data structures as:

  1. Using Slices 
  2. Using Structures
  3. Using LinkList

1. Implement Queue Using Slices in Go Language:

Implementing queue using a simple slice in which enqueueing and dequeuing operations are done using functions. and Underflow(queue is empty) is checked during dequeuing operation.

Go




package main
  
import "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, []int) {
element := queue[0] // The first element is the one to be dequeued.
if len(queue) == 1 {
 var tmp = []int{}
 return element, tmp
  
}
  
return element, queue[1:] // Slice off the element once it is dequeued.
}
  
func main() {
var queue = make([]int, 0)
  
queue = enqueue(queue, 10)
  
fmt.Println("After pushing 10 ", queue)
queue = enqueue(queue, 20)
  
fmt.Println("After pushing 20 ", queue)
queue = enqueue(queue, 30)
  
fmt.Println("After pushing 30 ", queue)
  
ele, queue := dequeue(queue)
fmt.Println("Queue After removing", ele, " :", queue)
  
queue = enqueue(queue, 40)
fmt.Println("After pushing 40 ", queue)
}


Output:
Enqueued: 10
After pushing 10  [10]
Enqueued: 20
After pushing 20  [10 20]
Enqueued: 30
After pushing 30  [10 20 30]
Queue After removing 10  : [20 30]
Enqueued: 40
After pushing 40  [20 30 40]

Note: In this, the problem is we can not define the size or capacity of the queue. However, it can be done by defining the queue as make([]int, 0, 10) where the third parameter determines capacity but the problem arises when capacity dynamically increases in an overflow condition.

2. Using Structures:

To overcome the problem in the earlier one, use Structures instead which consist of 

  • Elements i.e. queue Elements
  • Size i.e. Capacity of 

Use Pointers to directly change the queue without returning it every time and, check for both overflow and underflow conditions:

Go




package main
  
import (
    "errors"
    "fmt"
)
  
type Queue struct {
    Elements []int
    Size     int
}
  
func (q *Queue) Enqueue(elem int) {
    if q.GetLength() == q.Size {
        fmt.Println("Overflow")
        return
    }
    q.Elements = append(q.Elements, elem)
}
  
func (q *Queue) Dequeue() int {
    if q.IsEmpty() {
        fmt.Println("UnderFlow")
        return 0
    }
    element := q.Elements[0]
    if q.GetLength() == 1 {
        q.Elements = nil
        return element
    }
    q.Elements = q.Elements[1:]
    return element // Slice off the element once it is dequeued.
}
  
func (q *Queue) GetLength() int {
    return len(q.Elements)
}
  
func (q *Queue) IsEmpty() bool {
    return len(q.Elements) == 0
}
  
func (q *Queue) Peek() (int, error) {
    if q.IsEmpty() {
        return 0, errors.New("empty queue")
    }
    return q.Elements[0], nil
}
  
func main() {
    queue := Queue{Size: 3}
    fmt.Println(queue.Elements)
    queue.Enqueue(1)
    fmt.Println(queue.Elements)
    queue.Enqueue(2)
    fmt.Println(queue.Elements)
    queue.Enqueue(3)
    fmt.Println(queue.Elements)
    queue.Enqueue(5)
    fmt.Println(queue.Elements)
    elem := queue.Dequeue()
    fmt.Println(elem)
    fmt.Println(queue.Elements)
    queue.Enqueue(9)
    fmt.Println(queue.Elements)
    elem = queue.Dequeue()
    fmt.Println(elem)
    fmt.Println(queue.Elements)
  
}


Output:
[]
[1]
[1 2]
[1 2 3]
Overflow
[1 2 3]
1
[2 3]
[2 3 9]
2
[3 9]

Note: We used to compare the length of elements to the size(Capacity defined) of queue structure which is more good to use.

3. Using LinkList:

Go




package main
import "container/list"
import "fmt"
  
func main() {
    // new linked list
    queue := list.New()
  
    // Simply append to enqueue.
    queue.PushBack(10)
    queue.PushBack(20)
    queue.PushBack(30)
  
    // Dequeue
    front:=queue.Front()
    fmt.Println(front.Value)
    queue.Remove(front)
}


Output:
10

Note: In this also the capacity problem arises and to overcome that, there is a need to initialize a different variable and compare the length of the LinkList before every pushback.



Previous Article
Next Article

Similar Reads

Should we declare as Queue or Priority Queue while using Priority Queue in Java?
Queue: Queue is an Interface that extends the collection Interface in Java and this interface belongs to java.util package. A queue is a type of data structure that follows the FIFO (first-in-first-out ) order. The queue contains ordered elements where insertion and deletion of elements are done at different ends. Priority Queue and Linked List are
3 min read
What is Priority Queue | Introduction to Priority Queue
A priority queue is a type of queue that arranges elements based on their priority values. Elements with higher priority values are typically retrieved before elements with lower priority values. In a priority queue, each element has a priority value associated with it. When you add an element to the queue, it is inserted in a position based on its
15+ min read
Stack and Queue in Python using queue Module
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java. 1.
3 min read
Check if a queue can be sorted into another queue using a stack
Given a Queue consisting of first n natural numbers (in random order). The task is to check whether the given Queue elements can be arranged in increasing order in another Queue using a stack. The operation allowed are: Push and pop elements from the stack Pop (Or Dequeue) from the given Queue. Push (Or Enqueue) in the another Queue. Examples : Inp
9 min read
Reversing a Queue using another Queue
Given a queue. The task is to reverse the queue using another empty queue. Examples: Input: queue[] = {1, 2, 3, 4, 5} Output: 5 4 3 2 1 Input: queue[] = {10, 20, 30, 40} Output: 40 30 20 10 Approach: Given a queue and an empty queue.The last element of the queue should be the first element of the new queue.To get the last element there is a need to
5 min read
Advantages of circular queue over linear queue
Linear Queue: A Linear Queue is generally referred to as Queue. It is a linear data structure that follows the FIFO (First In First Out) order. A real-life example of a queue is any queue of customers waiting to buy a product from a shop where the customer that came first is served first. In Queue all deletions (dequeue) are made at the front and a
3 min read
Difference between Queue and Deque (Queue vs. Deque)
Queue: The queue is an abstract data type or linear data structure from which elements can be inserted at the rear(back) of the queue and elements can be deleted from the front(head) of the queue. The operations allowed in the queue are:insert an element at the reardelete element from the frontget the last elementget the first elementcheck the size
3 min read
Why can't a Priority Queue wrap around like an ordinary Queue?
Priority Queue: A priority queue is a special type of queue in which each element is assigned a priority value. And elements are served based on their priority. This means that elements with higher priority are served first. However, if elements with the same priority occur, they will be served in the order in which they were queued. A priority que
3 min read
Can we use Simple Queue instead of Priority queue to implement Dijkstra's Algorithm?
What is Dijkstra's Algorithm? Dijkstra's Algorithm is used for finding the shortest path between any two vertices of a graph. It uses a priority queue for finding the shortest path. For more detail, about Dijkstra's Algorithm, you can refer to this article. Why Dijkstra's Algorithm uses a Priority Queue? We use min heap in Dijkstra's Algorithm beca
2 min read
Turn a Queue into a Priority Queue
What is Queue?Queue is an abstract data type that is open at both ends. One end is always used to insert data (enqueue) which is basically the rear/back/tail end and the other which is the front end is used to remove data (dequeue). Queue follows First-In-First-Out (FIFO) methodology, i.e., "the data item stored first will be accessed first". Decla
9 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg