The list container in Go

Lists are an important aspect of programming. It is one of the most important data structures used today. In this post, we are going to explore about lists in Go.

The “container/list” package

To use lists in Go, we import the list package inside the container package. Then we can use the lists in Go by using the built-in data-type and its functions.

import "container/list"

What is a List in Golang?

A list is essentially a linked list in Go programming. There are two structs in this package which defines the list item and the list itself. Those structs are the Element and List.

Initializing a list in Go

Here is the way to initialize an empty list in Go. The list’s head and tail will be nil as the list contains nothing.

l := list.New()    // Initialize an empty list
fmt.Println(l)      // &{{0x43e280 0x43e280 <nil> <nil>} 0}

Items in the front and back

The front and back functions get us the items in the front and back respectively. Here it being an empty list both of the items are nil.

fmt.Println(l.Front())      // <nil>
fmt.Println(l.Back())       // <nil>

Adding items to the list

There are many ways to add items to a list. Here are the ways to do that.

1. Add items to the front

The PushFront function takes an item and pushes it to the front of the list.

l.PushFront(10)
fmt.Println(l.Front())       // &{0x43e280 0x43e280 0x43e280 10}

An entire list can be pushed in front of another list using the PushFrontList function. Be cautious as the list that will be inserted must be initialized properly.

l.PushFrontList(l2)    // where l2 is another list

2. Add items to the back

The PushBack function takes an item and pushes it to the back.

package main

import (
	"fmt"
	"container/list"
)

func main() {
	l := list.New()
	l.PushBack(10)
	l.PushBack(12)
	l.PushBack(14)
	for e := l.Front(); e != nil; e = e.Next() {
		fmt.Println(e)
	}
	
	// &{0x43e2c0 0x43e280 0x43e280 10}
	// &{0x43e2e0 0x43e2a0 0x43e280 12}
	// &{0x43e280 0x43e2c0 0x43e280 14}
}

The PushBackList does the same but takes an entire list and adds it to the list at the back.

l.PushBackList(l2)  // l2 is a list

Remove items from the list

The remove function simply removes the element passed into it from the list. Here it is in action.

package main

import (
	"fmt"
	"container/list"
)

func main() {
	l := list.New()

        // store the reference
	v := l.PushBack(10)
	fmt.Println(l.Front())      // &{0x43e280 0x43e280 0x43e280 10}
       
        // remove using the reference
	l.Remove(v)
	fmt.Println(l.Front())      // <nil>
}

These are the common ways lists are handled in Go.

Further Reading: Iterating a Map in Golang