programming

Get to know Container List and Sort in Golang

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.

package main

import ("fmt" ; "container/list")

func main() {
     var x list.List
     x.PushBack(1)
     x.PushBack(2)
     x.PushBack(3)
     for e := x.Front(); e != nil; e=e.Next() {
           fmt.Println(e.Value.(int))
} }

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

➜  12-libary-container-sort git:(main) ✗ go run main.go 
1
2
3

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.

package main

import (
	"fmt"
	"sort"
)

type Orang struct {
	Nama string
	Umur int
}
type ByNama []Orang

func (this ByNama) Len() int {
	return len(this)
}
func (this ByNama) Less(i, j int) bool {
	return this[i].Nama < this[j].Nama
}
func (this ByNama) Swap(i, j int) {
	this[i], this[j] = this[j], this[i]
}

func main() {
	kids := []Orang{
		{"Jill", 9},
		{"Jack", 10},
	}
	sort.Sort(ByNama(kids))
	fmt.Println(kids)
}

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:

type ByUmur []Orang

func (this ByUmur) Len() int {
	return len(this)
}
func (this ByUmur) Less(i, j int) bool {
	return this[i].Umur < this[j].Umur
}
func (this ByUmur) Swap(i, j int) {
	this[i], this[j] = this[j], this[i]
}
comments powered by Disqus