In the Go programming language, the container/list package provides a circular doubly linked list implementation. This type of data structure can be more performant for certain operations compared to slices. In this article, we will explore how to use this package to create and manipulate in-memory lists.
What is a Doubly Linked List?
A doubly linked list is a sequence of elements where each element points to both its predecessor and successor. In the context of the container/list package, this means that you can efficiently insert or delete elements at any position in constant time if you have the pointer to the position.
Importing the Package
Before you can begin using the container/list package, you need to import it into your Go application. Here's how you can do that:
import (
"container/list"
)
Creating a List
To create a new list, you simply call list.New() which returns a pointer to a List. Here is an example of how to create an empty list:
package main
import (
"container/list"
"fmt"
)
func main() {
myList := list.New()
fmt.Println("List created", myList)
}
Adding Elements
Once you have a list, you can start adding elements to it. You can add elements to the front or the back of the list:
myList.PushBack("Go")
myList.PushFront("Language")
myList.PushFront("Programming")
After executing the above commands, the list will contain elements in the order: Programming, Language, Go.
Iterating over a List
You can traverse through elements in a list starting from either the front or back. Here's an example that prints each element:
for e := myList.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value)
}
Removing Elements
Removing elements from the list involves getting a pointer to the element and then using the Remove method:
e := myList.Front() // Get the first element
myList.Remove(e) // Remove that element
The list automatically updates so the removed element is no longer accessible through the list primary operations.
Conclusion
The container/list package in Go is a powerful tool for constructing and managing in-memory lists where certain operations like insertions or deletions are frequently required. As you learn to leverage this package, you'll discover more extents to its powerful list infrastructure.