container/list
container/list is a doubly linked list. Elements are *list.Element nodes. Use it when you must insert or remove from the middle in constant time and you already hold the node. Prefer a slice for almost everything else.
Detailed Explanation
A linked list stores each value in a node with pointers to the next and previous node. list.New() creates an empty list. PushBack, PushFront, InsertAfter, and Remove move nodes. Front and Back are the ends. There is no index: you walk with e = e.Next().
Values are any. e.Value is an interface. You assert to your type on every read. That boxing is one reason lists lose to []T in Go. A slice of structs is contiguous, typed, and ranges without assertions.
When a list wins. An LRU cache holds a node pointer in a map and moves that node to the front on access. Remove plus PushFront is O(1) if you have the *Element. A slice would need copy to close the gap. The standard library's container/list is the usual implementation for that cache.
When a slice wins. Iteration, random access, extra space, and almost every algorithm problem. A []T with an index is simpler, faster, and does not allocate a node per element. If you are reaching for container/list because you know linked lists from a textbook, measure — in Go the textbook answer is often wrong.
Not safe for concurrent use. Same as a slice: lock if shared.
What it costs. Each Push* allocates a node. Each value is boxed in any. Walking the list misses cache. A slice of a million integers is one allocation and sequential access. A list of a million integers is a million nodes. Use the list when the O(1) middle update matters and n is moderate.
Code Examples
package main
import (
"container/list"
"fmt"
)
func main() {
l := list.New()
e := l.PushBack("b")
l.PushFront("a")
l.InsertAfter("c", e)
for n := l.Front(); n != nil; n = n.Next() {
fmt.Println(n.Value)
}
}func remove(l *list.List, e *list.Element) {
if e != nil {
l.Remove(e)
}
}Common Gotchas
`e.Value` is `any`
a wrong assertion panics. Keep one list per element type and assert in one helper.
`Remove` of an element from the wrong list is undefined in older docs and a no-op or panic depending on version
only remove elements you got from this list.
`Front()` on an empty list is nil
calling `Front().Value` panics. Check nil.
Prefer `[]T` unless you have a node pointer you must move in O(1)
Prefer `[]T` unless you have a node pointer you must move in O(1)