How to implement a queue (First-In-First-Out) using a slice in Golang?

To implement a queue (First-In-First-Out) using a slice in Go, you can follow these steps:

  1. Define a struct type for your queue that holds the underlying slice and two integer variables to track the front and rear indices of the queue:
type Queue struct { items []int front int rear int }
  1. Define methods for the queue struct to perform queue operations such as Enqueue, Dequeue, IsEmpty, Size, and Front.
// Enqueue adds an element to the rear of the queue func (q *Queue) Enqueue(item int) { q.items = append(q.items, item) q.rear++ } // Dequeue removes and returns the front element of the queue func (q *Queue) Dequeue() int { if q.IsEmpty() { panic("Queue is empty") } item := q.items[q.front] q.items = q.items[q.front+1:] q.rear-- return item } // IsEmpty checks if the queue is empty func (q *Queue) IsEmpty() bool { return q.front == q.rear } // Size returns the number of elements in the queue func (q *Queue) Size() int { return q.rear - q.front } // Front returns the front element of the queue without removing it func (q *Queue) Front() int { if q.IsEmpty() { panic("Queue is empty") } return q.items[q.front] }
  1. Create a new instance of the Queue struct and use the Enqueue and Dequeue methods to add and remove elements from the queue:
queue := Queue{} queue.Enqueue(1) queue.Enqueue(2) queue.Enqueue(3) fmt.Println(queue.Front()) // Output: 1 fmt.Println(queue.Dequeue()) // Output: 1 fmt.Println(queue.Dequeue()) // Output: 2 fmt.Println(queue.Size()) // Output: 1 fmt.Println(queue.IsEmpty()) // Output: false

Now you have successfully implemented a queue (First-In-First-Out) using a slice in Go.