How to Create a Queue in Go
A queue is a very useful data structure where one can store, add, and remove objects with the “First in, First out” (FIFO) principle. Queues are very useful for basic algorithms (such as bread-first search), so it is therefore worth learning how to implement them in Go. The best way to implement a queue using Go is by creating a struct
. You can read more about structs
in Go in this blog post.
The first step is to create the struct
and call it Queue
.
type Queue struct {
elements []int // stores the objects in the queue
size int // the maximum size of the queue
}
After defining the struct, we can define its methods, namely GetLength()
, Enqueue()
, and Dequeue()
. By writing (q *Queue)
when defining the function (where q
denotes a Queue
object), we specify that the method belongs to the struct
.
func (q *Queue) GetLength() int {
return len(q.elements) // return current length of the queue
}
func (q *Queue) Enqueue(element int) {
if q.GetLength() == q.size { // if the queue is at max length, don't add new element
fmt.Println("Queue is full")
return
} else {
q.elements = append(q.elements, element)
return
}
}
func (q *Queue) Dequeue() int {
if q.GetLength() == 0 { // if queue is empty, there is nothing to dequeue
fmt.Println("Queue is empty")
return 0
} else if q.GetLength() == 1 {
temp := q.elements[0]
q.elements = q.elements[:0] // if current length is 1, queue becomes empty
return temp
} else {
temp := q.elements[0]
q.elements = q.elements[1:]
return temp // return the dequeued element
}
}
The last step is to define the main function that will create and modify a queue
object:
import "fmt"
func main() {
q := Queue{size: 3} // creates a queue with a max size of 3
q.Enqueue(1)
q.Enqueue(2)
q.Enqueue(3)
q.Enqueue(4) // Queue is full
fmt.Print(q.elements) // [1, 2, 3]
elem1 := q.Dequeue()
elem2 := q.Dequeue()
elem3 := q.Dequeue()
fmt.Println(elem1, elem2, elem3) // 1, 2, 3
q.Dequeue() // Queue is empty
}
The queue
data structure is now implemented!
Note that the stack
data structure is very similar in implementation. Only the Dequeue()
method needs to be changed to remove the last element in elements
instead of the first.