Home >Backend Development >Golang >How to Implement a FIFO Queue in Go Using a Slice?
FIFO Queue Implementation in Go Using Slice
Implementing a First-In-First-Out (FIFO) queue in Go requires a simple and efficient container type. Go offers three options: heap, list, and vector. However, for a basic and fast FIFO queue, a slice is the most suitable choice.
The following code demonstrates how to use a Go slice as a FIFO queue:
package main import ( "fmt" ) func main() { // Create an empty slice as the queue queue := make([]int, 0) // Push an element to the queue (enqueue) queue = append(queue, 1) // Get the first element without removing it (peek) x := queue[0] // Remove the first element (dequeue) queue = queue[1:] // Check if the queue is empty if len(queue) == 0 { fmt.Println("Queue is empty!") } }
The slice's append and slicing operations ensure that the FIFO behavior is maintained, making it a reliable and efficient implementation for simple queue requirements.
The above is the detailed content of How to Implement a FIFO Queue in Go Using a Slice?. For more information, please follow other related articles on the PHP Chinese website!