Enqueue values at the back and dequeue them from the front in first-in, first-out order.

Algorithm

Basic Implementation

basic.go
package main

import (
	"fmt"
	"strings"
)

func render(values []int) string {
	parts := make([]string, 0, len(values))
	for _, value := range values {
		parts = append(parts, fmt.Sprint(value))
	}
	return strings.Join(parts, " -> ")
}

func main() {
	queue := []int{}
	for _, value := range []int{10, 20, 30} { queue = append(queue, value) }
	removed := []int{}
	for len(queue) > 0 { removed = append(removed, queue[0]); queue = queue[1:] }
	fmt.Println(render(removed))
}

The queue keeps the oldest value at the front and adds new values at the back.

Step 1 - Enqueue 10, 20, 30

New values join at the back. The oldest value, 10, stays at the front.

Queue after three enqueues: front 10, then 20, then back 30.nextnext10front2030back

Step 2 - Dequeue removes 10

Removing from the front returns 10 and makes 20 the new front.

After one dequeue: removed is 10; front moves to 20.next10removed20front30back

Complexity

  • Time: O(1) per operation with a real queue
  • Space: O(n)

Implementation notes

  • Go starts with queue := []int{} and appends 10, 20, and 30; append may grow the backing array, but the visible queue state becomes [10, 20, 30].
  • Dequeue reads the front slot with queue[0], appends that value to removed, then advances the slice header with queue = queue[1:].
  • The loop guard len(queue) > 0 prevents an empty-slice index. Because reslicing keeps a view of the same backing array, a long-lived queue could retain dequeued storage; this tiny replay drains it immediately.
  • The trace records the empty queue, the enqueue batch, one front removal to removed=[10] with queue=[20, 30], then the remaining removals to removed=[10, 20, 30] and queue=[].
  • render allocates a []string, converts each int with fmt.Sprint, joins with strings.Join(parts, " -> "), and fmt.Println prints 10 -> 20 -> 30.
front The front is the oldest value still waiting in the queue.
FIFO A queue removes values in first-in, first-out order.