Queue Implementation in Golang

1. Introduction

A Queue is a linear data structure that follows the First In First Out (FIFO) principle. This means the first element added to the queue is the first one to be removed. It has two primary operations: enqueue, which adds an element to the rear end, and dequeue, which removes the front element.

2. Implementation Steps

1. Define a Queue type using a slice to hold its elements.

2. Implement the enqueue method to add an element to the rear of the queue.

3. Implement the dequeue method to remove and return the front element. Check for queue underflow.

4. Optionally, add a method to check if the queue is empty and another to view the front element without dequeuing it.

3. Implementation in Golang

package main
import (
	"fmt"
	"errors"
)
type Queue []int
func (q *Queue) Enqueue(v int) {
	*q = append(*q, v)
}
func (q *Queue) Dequeue() (int, error) {
	if len(*q) == 0 {
		return 0, errors.New("Queue is empty")
	}
	res := (*q)[0]
	*q = (*q)[1:]
	return res, nil
}
func (q *Queue) Front() (int, error) {
	if len(*q) == 0 {
		return 0, errors.New("Queue is empty")
	}
	return (*q)[0], nil
}
func (q *Queue) IsEmpty() bool {
	return len(*q) == 0
}
func main() {
	var queue Queue
	queue.Enqueue(5)
	queue.Enqueue(10)
	queue.Enqueue(15)
	fmt.Println("Front of the Queue:", queue.Front())
	fmt.Println("Queue:", queue)
	dequeued, _ := queue.Dequeue()
	fmt.Println("Dequeued:", dequeued)
	fmt.Println("Queue after Dequeue:", queue)
}

Output:

Front of the Queue: 5
Queue: [5 10 15]
Dequeued: 5
Queue after Dequeue: [10 15]

Explanation:

1. A new data type Queue is defined as a slice of integers.

2. The Enqueue method appends a value to the end of the slice, effectively adding it to the rear of the queue.

3. The Dequeue method checks if the queue is empty by verifying if the length of the slice is 0. If it's not empty, it retrieves the first element and updates the slice to remove that first element.

4. The Front method returns the first element of the slice without removing it.

5. The IsEmpty method checks if the queue is empty by verifying if the length of the slice is 0.

6. The main function showcases the functionality of the queue, its methods, and the expected output.

The presented Queue implementation in Golang is a simple way to utilize the FIFO principle in programming tasks and applications.


Comments