Learn How to use list in Golang
In this article, you will learn about how to use the list in the Go language.
In the Go language, lists are referred to as linked lists which is one of the most important data structures used today. If you want to use the list in the Go language you need to import the list package inside the container package. This package refers to two structs one is a list item and another one is the list itself. See the below example of importing packages and initializing the list in the Go language:
// Import packages
import "container/list"
// Initializing list
myList := list.New()
You can do many things with the help of a list such as add items, remove items and, so on. The list in the Go language lets you add items to the list. You can add items in the front or back of a list. Let’s see how to add an item in the front of a list first in the below example:
package main
import (
"container/list"
"fmt"
)
func main() {
myList := list.New()
myList.PushFront(15)
for l := myList.Front(); l != nil; l = l.Next() {
fmt.Println(l)
}
}
// Output : &{0xc000072480 0xc000072480 0xc000072480 15}
You can also add an item in the back of a list in the Go language. To do so see the below code example:
package main
import (
"container/list"
"fmt"
)
func main() {
myList := list.New()
myList.PushBack(22)
myList.PushBack(34)
myList.PushFront(15)
for l := myList.Front(); l != nil; l = l.Next() {
fmt.Println(l)
}
}
/*
Output:
&{0xc0000724b0 0xc000072480 0xc000072480 15}
&{0xc0000724e0 0xc000072510 0xc000072480 22}
&{0xc000072480 0xc0000724b0 0xc000072480 34}
*/
Here, you can see that element 15 has been printed in the front, and rest of them has been printed back because of we have used PushBack() and PushFront() function.
If you want to remove an element from the list, you just need to apply the remove function and it will simply remove an element from the list for you. See the below code example to get a clear idea:
package main
import (
"container/list"
"fmt"
)
func main() {
myList := list.New()
myList.PushBack(22)
myList.PushBack(34)
rmv := myList.PushFront(15)
// removing an element
myList.Remove(rmv)
for l := myList.Front(); l != nil; l = l.Next() {
fmt.Println(l)
}
}
/*
Output:
&{0xc0000724e0 0xc000072510 0xc000072480 22}
&{0xc000072480 0xc0000724b0 0xc000072480 34}
*/
Here, we have removed an element by using the reference of the element that we want to remove and use it in the remove function. Finally, you can see that the element has been removed from the list and it has printed two elements instead of printing three.