Queue in Go Language
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:
- Using Slices
- Using Structures
- 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.
Output: Enqueued: 10 After pushing 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:
Output:   [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:
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.
Please Login to comment...