Use container/list, heap and ring
Use container/list, heap and ring
Go provides specialized structures in container/list, container/heap and container/ring. A list is a doubly linked sequence with handles to elements; a heap supports priority-based removal through heap.Interface; a ring represents a circular list. These packages predate generics and expose some values as any, so use type assertions carefully.
package main
import ( "container/list" "container/ring" "fmt")
func main() { l := list.New() a := l.PushBack("A") l.PushBack("B") l.MoveToBack(a) for e := l.Front(); e != nil; e = e.Next() { fmt.Println(e.Value) } r := ring.New(3) for i := 1; i <= 3; i++ { r.Value = i r = r.Next() } r.Move(1).Do(func(v any) { fmt.Print(v, " ") }) fmt.Println()}PushBack returns an element handle; MoveToBack moves that element without searching for it. Front returns nil for an empty list. Ring.New creates a circular sequence of n entries (nil if n <= 0); Move returns another position, and Do visits each entry once. Do not use an unbounded Next loop to traverse a ring. Use a slice for ordinary indexed access.
Expected output:
BA2 3 1Maintain a priority queue
package main
import ( "container/heap" "fmt")
type MinHeap []int
func (h MinHeap) Len() int { return len(h) }func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] }func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }func (h *MinHeap) Push(x any) { *h = append(*h, x.(int)) }func (h *MinHeap) Pop() any { old := *h; n := len(old); x := old[n-1]; *h = old[:n-1]; return x }func main() { h := MinHeap{7, 2, 5} heap.Init(&h) heap.Push(&h, 1) for h.Len() > 0 { fmt.Println(heap.Pop(&h).(int)) }}Len, Less and Swap satisfy sort.Interface; Push and Pop complete heap.Interface. The implementation Pop removes the last element after the package moves the minimum there. Use heap.Push and heap.Pop, not the raw methods, to preserve the heap invariant. Never pop an empty heap; this example guards length. The asserted type is known because only int values are inserted. For reference-bearing elements clear removed slots when appropriate.
Expected output:
1257Try it locally
Create an empty list, insert "first" and "last", remove the first using its returned handle and print the remaining value and length.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Core library 06: Use container/list, heap and ring
Check the lesson objective before moving on.
Which function should callers use to remove the minimum from a nonempty initialized min-heap?
How can a ring be visited exactly once?