Generic FIFO queue with multiple backing implementations.
Queue is a generic first-in, first-out (FIFO) data structure. Elements are
removed in the same order they were inserted. The library provides four
implementations that share a common interface, each with different allocation
strategies so you can choose the best fit for your workload.
Some implementations also satisfy container.Countable, which adds a Len()
method. You should always check for it at runtime via a type assertion rather
than relying on a specific implementation.
if c, ok := q.(container.Countable); ok { fmt.Printf("elements in queue: %d\n", c.Len())}
Len() is not part of the core Queue interface because not all
implementations provide it. Always guard the call with a type assertion as
shown above.
package mainimport ( "fmt" "github.com/fgm/container" "github.com/fgm/container/queue")type Task intfunc main() { const sizeHint = 100 q := queue.NewSliceQueue[Task](sizeHint) q.Enqueue(Task(1)) q.Enqueue(Task(2)) q.Enqueue(Task(3)) // Optionally check the length if the implementation supports it. if c, ok := q.(container.Countable); ok { fmt.Printf("elements in queue: %d\n", c.Len()) } // Drain the queue. for { e, ok := q.Dequeue() if !ok { break } fmt.Printf("dequeued: %v\n", e) } // Dequeue on an empty queue returns the zero value and ok=false. e, ok := q.Dequeue() fmt.Printf("empty dequeue -> value: %v, ok: %t\n", e, ok)}// Output:// elements in queue: 3// dequeued: 1// dequeued: 2// dequeued: 3// empty dequeue -> value: 0, ok: false
Queue is not concurrency-safe. Do not share a Queue across goroutines
without external synchronization. For concurrent producer-consumer scenarios,
use WaitableQueue instead.