Queues in Go: An Introduction and Implementation

Introduction to Queues

Hello there! Today, we will unveil queues in coding, likening them to a line in a coffee shop or a queue of print requests. Queues in computer science are First-In, First-Out (FIFO) structures. Consider this example: You're at a theme park — the first person in line for the roller coaster gets on first. Today's lesson revolves around this straightforward yet powerful concept. So, let's dive in!

Implementing a Queue in Go

Let's delve into implementing queues in Go using a struct to define a Queue:

type Queue struct {
    front, rear, size, capacity int
    array                       []int
}

func NewQueue(capacity int) *Queue {
    return &Queue{
        front:    0,
        rear:     0,
        size:     0,
        capacity: capacity,
        array:    make([]int, capacity),
    }
}

func (q *Queue) IsFull() bool {
    return q.size == q.capacity
}

func (q *Queue) IsEmpty() bool {
    return q.size == 0
}

Explanations of the `Queue` Fields

  • front: This field marks the starting index of the queue where the elements are dequeued. It helps keep track of the next element to be removed.

  • rear: This field marks the position where the new element will be enqueued. It points to the next available spot for insertion.

  • size: This keeps track of the number of elements currently in the queue. By maintaining the size, we can easily verify if the queue is empty or full.

  • capacity: This sets the maximum number of elements the queue can hold. It helps in determining if an enqueue operation can be performed.

  • array: This slice is the underlying data storage that holds the elements of the queue. It is initialized with a fixed capacity.

In this implementation, front and rear utilize modular arithmetic to maintain a circular queue structure, allowing efficient use of the predefined capacity. The IsFull() method checks if the queue has reached its capacity, while the IsEmpty() method verifies if there are no elements to dequeue.

Queue Enqueue Operation

Enqueue denotes adding an item to the queue — the item lines up at the back of the queue. Here's how it plays out in our Queue implementation:

func (q *Queue) Enqueue(item int) error {
    if q.IsFull() {
        return fmt.Errorf("queue is full")
    }
    q.array[q.rear] = item
    q.rear = (q.rear + 1) % q.capacity
    q.size++
    return nil
}

q.rear = (q.rear + 1) % q.capacity ensures the rear pointer wraps around to the start of the queue when surpassing the maximum index, maintaining a circular behavior.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal