Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
24 Oct 2022 · 3 min read ·Article 17 / 119
Go

Get to know Container List and Sort in Golang

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

In addition to arrays and maps, Go has several more collections available under the container package. We’ll look at the container/list package as an example.

Package List

The container/list library implements a doubly linked list. Linked list or what we often say Linked List is a type of data structure that looks like this:

List

Each node of the list contains a value (1, 2, or 3 in this case) and a pointer to the next node (point). Since this is a doubly linked list, each node will also have a pointer to the previous node. This list can be created with the program below.

go
 1package main
 2
 3import ("fmt" ; "container/list")
 4
 5func main() {
 6     var x list.List
 7     x.PushBack(1)
 8     x.PushBack(2)
 9     x.PushBack(3)
10     for e := x.Front(); e != nil; e=e.Next() {
11           fmt.Println(e.Value.(int))
12} }

So we can see the results if we run the program above

bash
1➜  12-libary-container-sort git:(main) ✗ go run main.go 
21
32
43
A zero value for a list is an empty list (*lists can also be created using list.New). Values are added to the list using the PushBack function. We iterate over each item in the list by getting the first element, and following all the links until we reach nil.

Package Sort

The sort package contains functions for sorting data according to our needs. There are some predefined sorting functions (for int and float). The following is an example of how to sort our data.

go
 1package main
 2
 3import (
 4	"fmt"
 5	"sort"
 6)
 7
 8type Orang struct {
 9	Nama string
10	Umur int
11}
12type ByNama []Orang
13
14func (this ByNama) Len() int {
15	return len(this)
16}
17func (this ByNama) Less(i, j int) bool {
18	return this[i].Nama < this[j].Nama
19}
20func (this ByNama) Swap(i, j int) {
21	this[i], this[j] = this[j], this[i]
22}
23
24func main() {
25	kids := []Orang{
26		{"Jill", 9},
27		{"Jack", 10},
28	}
29	sort.Sort(ByNama(kids))
30	fmt.Println(kids)
31}

The Sort function in the sort package takes sort.Interface and sorts it. Sort.Interface requires 3 methods: Len, Less and Swap. To define our own sorting, we create a new type (ByName) and make it equivalent to a chunk of what we want to sort. Then we define 3 methods.

We can also sort the kids data based on age. So, we also need to define the ByAge type so that the sorting is adjusted to the age of the people’s data. Below we need to add:

go
 1type ByUmur []Orang
 2
 3func (this ByUmur) Len() int {
 4	return len(this)
 5}
 6func (this ByUmur) Less(i, j int) bool {
 7	return this[i].Umur < this[j].Umur
 8}
 9func (this ByUmur) Swap(i, j int) {
10	this[i], this[j] = this[j], this[i]
11}

Related Articles

💬 Comments