I\'m learning Go, and as an exercise I wanted to implement a linked list. For reference I looked at the official Go code (https://golang.org/src/container/list/list.go) . On
Golang garbage collector is based on the tri-color mark-and-sweep algorithm. In short, every memory you're program use is associated to a color. The color determine if the memory shall be garbaged or not.
This algorithm will flag a memory to be freed if this memory is not referenced somewhere (directly and indirectly). But if we take a look at the code:
e.prev.next = e.next
e.next.prev = e.prev
This copy the pointer in e.next into e.prev.next. Now, let's say you want to update e.prev.next by a new fully created element.
The previously removed element won't be garbaged because it is still referenced by e.next.
This is why those lines exist:
e.next = nil // avoid memory leaks
e.prev = nil // avoid memory leaks
This prevent from leaving old references, and thus prevent from memory leaks.