Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Deque Implementation in Go

11 min readbeginner
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Deque runs in O(1) time and O(n) space, in Go as in every other language.
  • ✓There is no deque type in the standard library. container/list is a doubly linked list with PushFront, PushBack, Front, Back and Remove, and it satisfies the ADT, but it stores interface{} in pre-generics form (list.Element.Value is any) so every element is boxed.
  • ✓Reviewers want a generic struct over []T with head and size, growth by append-into-a-new-slice, and PopFront returning (T, bool) in the comma-ok shape rather than panicking.
  • ✓The Go trap: The Go-specific trap is the typed nil inside an interface: if T is an interface type, a stored typed nil pointer comes back non-nil, so a Deque[error] holding a (*MyErr)(nil) yields a value where v != nil is true and the caller handles an error that is not there.
  • ✓Elements are stored by value in one contiguous []T, so no boxing and one allocation per growth: a Deque[int] holds machine ints, unlike container/list which heap-allocates an Element per node and boxes into any.

What Deque actually is

A deque is an abstract data type offering push and pop at both the front and the back, each in amortised constant time, with indexing usually O(1) too. Two implementations dominate. A growable ring buffer stores elements in one contiguous block with head and tail indices that wrap modulo capacity; when full it allocates a larger block and copies, giving amortised O(1) by doubling. A chunked or blocked list stores fixed-size arrays in an index of block pointers, so growth appends a block and never moves existing elements. That choice is the whole story: the ring buffer wins on cache locality and loses on pointer/reference stability and on being non-contiguous after wrap; the chunked list keeps references valid and bounds worst-case latency. The eight languages diverge because they disagree on whether elements are values or references, whether stable addresses matter, whether iterator invalidation is a compile error or a runtime surprise, and whether a collection may hand out interior pointers at all.

Deque in Go: what you actually reach for

There is no deque type in the standard library. container/list is a doubly linked list with PushFront, PushBack, Front, Back and Remove, and it satisfies the ADT, but it stores interface{} in pre-generics form (list.Element.Value is any) so every element is boxed. The idiomatic answer is a slice-backed ring buffer you write yourself, generic since Go 1.18: type Deque[T any] struct { buf []T; head, size int }. Note that container/ring is a fixed-size circular list, not a growable deque, and channels are not a deque either since they are FIFO only.

Go implementation

Reviewers want a generic struct over []T with head and size, growth by append-into-a-new-slice, and PopFront returning (T, bool) in the comma-ok shape rather than panicking. They want the zero value usable, so var d Deque[int] works without a constructor. They reject container/list in new code for the boxing, reject d = d[1:] on a slice as a queue because the backing array is never reclaimed and the slice leaks, and reject exporting the buffer field.
go
package deque

// Generic since Go 1.18; the zero value is usable.
type Deque[T any] struct {
	buf  []T
	head int
	size int
}

func (d *Deque[T]) Len() int { return d.size }

func (d *Deque[T]) grow() {
	n := len(d.buf) * 2
	if n == 0 {
		n = 8
	}
	out := make([]T, n)
	for i := 0; i < d.size; i++ {
		out[i] = d.buf[(d.head+i)%len(d.buf)]
	}
	d.buf, d.head = out, 0
}

// Pointer receiver: a value receiver would drop these writes.
func (d *Deque[T]) PushBack(v T) {
	if d.size == len(d.buf) {
		d.grow()
	}
	d.buf[(d.head+d.size)%len(d.buf)] = v
	d.size++
}

// Comma-ok, not a panic: the empty case is the caller's to handle.
func (d *Deque[T]) PopFront() (T, bool) {
	var zero T
	if d.size == 0 {
		return zero, false
	}
	v := d.buf[d.head]
	// Zero the slot or the backing array pins the element forever.
	d.buf[d.head] = zero
	d.head = (d.head + 1) % len(d.buf)
	d.size--
	return v, true
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Go-specific trap

The Go-specific trap is the typed nil inside an interface: if T is an interface type, a stored typed nil pointer comes back non-nil, so a Deque[error] holding a (*MyErr)(nil) yields a value where v != nil is true and the caller handles an error that is not there. The second is receiver and copy semantics: the methods must take *Deque[T], because a value receiver silently drops the head and size updates, and because the zero value is usable people copy the struct, where d2 := d1 duplicates head and size but shares one backing array so both deques write over each other. Keep *Deque[T] in maps too, since a map element is not addressable and a pointer method will not compile on it. Relatedly, s = s[1:] on a shared slice never returns front capacity, so a naive slice queue grows without bound.

Performance in Go, beyond the O(1)

Elements are stored by value in one contiguous []T, so no boxing and one allocation per growth: a Deque[int] holds machine ints, unlike container/list which heap-allocates an Element per node and boxes into any. Growth doubles and copies; the copy of a wrapped buffer is two copy calls. Each access costs a modulo or mask plus a bounds check that the compiler often cannot elide across the wrap. Zeroing popped slots costs one store and saves the GC from scanning dead pointers. The asymptotic cost is the same in every language, O(1) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Deque between languages.

Real-World Applications

Deque applies wherever its problem shape appears in your own code. In Go, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Deque helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Deque appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Deque over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Deque to build pattern recognition. In Go, demonstrate proficiency with goroutines and channels to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Go code that is both correct and maintainable.

Frequently Asked Questions

Which Go type or library should I use for Deque?

There is no deque type in the standard library. container/list is a doubly linked list with PushFront, PushBack, Front, Back and Remove, and it satisfies the ADT, but it stores interface{} in pre-generics form (list.Element.Value is any) so every element is boxed. The idiomatic answer is a slice-backed ring buffer you write yourself, generic since Go 1.18: type Deque[T any] struct { buf []T; head, size int }. Note that container/ring is a fixed-size circular list, not a growable deque, and channels are not a deque either since they are FIFO only.

What is the most common Go mistake when implementing Deque?

The Go-specific trap is the typed nil inside an interface: if T is an interface type, a stored typed nil pointer comes back non-nil, so a Deque[error] holding a (*MyErr)(nil) yields a value where v != nil is true and the caller handles an error that is not there. The second is receiver and copy semantics: the methods must take *Deque[T], because a value receiver silently drops the head and size updates, and because the zero value is usable people copy the struct, where d2 := d1 duplicates head and size but shares one backing array so both deques write over each other. Keep *Deque[T] in maps too, since a map element is not addressable and a pointer method will not compile on it. Relatedly, s = s[1:] on a shared slice never returns front capacity, so a naive slice queue grows without bound.

How does Deque actually perform in Go?

Elements are stored by value in one contiguous []T, so no boxing and one allocation per growth: a Deque[int] holds machine ints, unlike container/list which heap-allocates an Element per node and boxes into any. Growth doubles and copies; the copy of a wrapped buffer is two copy calls. Each access costs a modulo or mask plus a bounds check that the compiler often cannot elide across the wrap. Zeroing popped slots costs one store and saves the GC from scanning dead pointers. Time complexity is O(1) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Studying for this? Replit free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.