container/list, container/ring, and container/heap

suggest change

While slices and maps are the primary collection types in Go, the standard library provides specialized abstract data structures under the container package:

  1. container/list: A doubly linked list supporting $O(1)$ insertions and removals anywhere in the list.
  2. container/ring: A circular list whose elements form a continuous ring.
  3. container/heap: A min-heap implementation for building priority queues.

1. container/list (Doubly Linked List)

A doubly linked list allows inserting, moving, and deleting elements anywhere in the list in $O(1)$ time without memory reallocations or shifting slice elements.

Basic Usage

package main

import (
	"container/list"
	"fmt"
)

func main() {
	// Create a new doubly linked list
	l := list.New()

	// Push elements
	e4 := l.PushBack("Fourth")       // Append to back
	e1 := l.PushFront("First")       // Prepend to front
	_ = l.InsertAfter("Second", e1)  // Insert after specific element
	_ = l.InsertBefore("Third", e4)  // Insert before specific element

	// Iterate forward from front to back
	fmt.Print("Forward: ")
	for e := l.Front(); e != nil; e = e.Next() {
		fmt.Printf("%v -> ", e.Value)
	}
	fmt.Println("nil")

	// Move an element to the front in O(1)
	l.MoveToFront(e4)

	// Remove an element in O(1)
	l.Remove(e1)

	// Iterate backward
	fmt.Print("Backward: ")
	for e := l.Back(); e != nil; e = e.Prev() {
		fmt.Printf("%v <- ", e.Value)
	}
	fmt.Println("nil")
}

Output:

Forward: First -> Second -> Third -> Fourth -> nil
Backward: Third <- Second <- Fourth <- nil

Classic Use Case: LRU Cache Eviction

container/list is the standard building block for Least Recently Used (LRU) caches. When an item is accessed, l.MoveToFront(e) moves it to the head in $O(1)$. When the cache reaches capacity, l.Remove(l.Back()) evicts the oldest item in $O(1)$.


2. container/ring (Circular List)

A ring is a circular buffer of fixed size where the last element points directly back to the first element. There is no head or tail.

Practical Example: Round-Robin Load Balancer

package main

import (
	"container/ring"
	"fmt"
)

func main() {
	servers := []string{"srv-1.internal", "srv-2.internal", "srv-3.internal"}

	// Create a ring of size 3
	r := ring.New(len(servers))

	// Populate ring elements
	for _, srv := range servers {
		r.Value = srv
		r = r.Next()
	}

	// Iterate across all elements using Do()
	fmt.Println("Available backend servers:")
	r.Do(func(p any) {
		fmt.Printf(" - %v\n", p)
	})

	// Simulate round-robin request dispatching
	fmt.Println("\nDispatching 6 incoming requests:")
	for i := 1; i <= 6; i++ {
		fmt.Printf("Request %d routed to: %v\n", i, r.Value)
		r = r.Next() // Advance to next server in O(1)
	}
}

Output:

Available backend servers:
 - srv-1.internal
 - srv-2.internal
 - srv-3.internal

Dispatching 6 incoming requests:
Request 1 routed to: srv-1.internal
Request 2 routed to: srv-2.internal
Request 3 routed to: srv-3.internal
Request 4 routed to: srv-1.internal
Request 5 routed to: srv-2.internal
Request 6 routed to: srv-3.internal

3. container/heap (Priority Queue)

container/heap provides heap operations (Push and Pop in $O(\log n)$) for any collection that implements heap.Interface. By default, Go's heap is a min-heap (the lowest value is at root index 0).

Implementing heap.Interface

heap.Interface requires five methods:

package main

import (
	"container/heap"
	"fmt"
)

type Task struct {
	Name     string
	Priority int // Lower number = higher priority
}

// PriorityQueue implements heap.Interface
type PriorityQueue []*Task

func (pq PriorityQueue) Len() int { return len(pq) }

// Less reports whether element at index i should sort before element at index j
func (pq PriorityQueue) Less(i, j int) bool {
	return pq[i].Priority < pq[j].Priority // Min-heap: lowest priority number first
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *PriorityQueue) Push(x any) {
	*pq = append(*pq, x.(*Task))
}

func (pq *PriorityQueue) Pop() any {
	old := *pq
	n := len(old)
	item := old[n-1]
	*pq = old[0 : n-1]
	return item
}

func main() {
	pq := &PriorityQueue{
		&Task{Name: "Send weekly newsletter", Priority: 3},
		&Task{Name: "Fix critical production outage", Priority: 1},
		&Task{Name: "Update dependencies", Priority: 4},
		&Task{Name: "Review pull request", Priority: 2},
	}

	// Initialize slice into a valid heap in O(n) time
	heap.Init(pq)

	// Insert a new task in O(log n) time
	heap.Push(pq, &Task{Name: "Hotfix database index", Priority: 1})

	// Pop tasks in prioritized order in O(log n) time
	fmt.Println("Processing tasks by priority:")
	for pq.Len() > 0 {
		task := heap.Pop(pq).(*Task)
		fmt.Printf("Priority %d: %s\n", task.Priority, task.Name)
	}
}

Output:

Processing tasks by priority:
Priority 1: Fix critical production outage
Priority 1: Hotfix database index
Priority 2: Review pull request
Priority 3: Send weekly newsletter
Priority 4: Update dependencies

When to Use container vs. Standard Slices

Structure Best Used When Avoid When
container/list Frequent $O(1)$ insertions, deletions, or moves in the middle of a collection (e.g. LRU cache) Sequentially scanning elements (slices have far superior CPU cache locality)
container/ring Circular fixed-size structures (e.g. round-robin scheduling, cyclic audio buffers) Variable-sized lists needing random indexing
container/heap Prioritized job scheduling, Dijkstra's algorithm, top-$K$ streaming elements Simple sorting once (use slices.Sort() instead)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents