How do I implement a generic deque in Go?

In Go, implementing a generic deque (double-ended queue) allows you to efficiently add and remove elements from both ends. Below is a simple implementation using Go's support for generics introduced in Go 1.18.

Generic Deque Implementation

package main import "fmt" type Deque[T any] struct { items []T } func NewDeque[T any]() *Deque[T] { return &Deque[T]{items: []T{}} } func (d *Deque[T]) PushFront(item T) { d.items = append([]T{item}, d.items...) } func (d *Deque[T]) PushBack(item T) { d.items = append(d.items, item) } func (d *Deque[T]) PopFront() (T, bool) { if len(d.items) == 0 { var zero T return zero, false } item := d.items[0] d.items = d.items[1:] return item, true } func (d *Deque[T]) PopBack() (T, bool) { if len(d.items) == 0 { var zero T return zero, false } item := d.items[len(d.items)-1] d.items = d.items[:len(d.items)-1] return item, true } func (d *Deque[T]) IsEmpty() bool { return len(d.items) == 0 } func (d *Deque[T]) Size() int { return len(d.items) } func main() { deque := NewDeque[int]() deque.PushBack(1) deque.PushBack(2) deque.PushFront(0) fmt.Println(deque.PopFront()) // Outputs: 0 fmt.Println(deque.PopBack()) // Outputs: 2 }

Go generics deque implementation double-ended queue Go data structures