GoGo

Go: Data structures – code examples

Contents

Working with slices

Data structures#slice#append#sort#arrayCompare in all languages
Use case: Manage collections of values: add, sort, search.
package main

import (
	"fmt"
	"slices"
)

func main() {
	zahlen := []int{5, 3, 8, 1}
	zahlen = append(zahlen, 10)
	slices.Sort(zahlen)
	fmt.Println(zahlen, len(zahlen))
}

Slices are Go's lists; append returns the slice and must be assigned. Output: [1 3 5 8 10] 5. There is no list comprehension – filter with a for loop (see the snippet "Filter and transform a slice").

Map

Data structures#map#dictionary#hashmapCompare in all languages
Use case: Store mappings, e.g. configurations or intermediate results.
package main

import "fmt"

func main() {
	person := map[string]string{"name": "Ada"}
	person["stadt"] = "London"
	for k, v := range person {
		fmt.Println(k, "=", v)
	}
	email, ok := person["email"]
	fmt.Printf("%q %v\n", email, ok)
}

The second return value (ok) tells you whether the key exists; missing keys yield the zero value (""). The order of range over maps is random.

Sort by a custom criterion

Data structures#sort#slices#cmp#struct
Use case: Order records, e.g. users by age or name.
package main

import (
	"cmp"
	"fmt"
	"slices"
	"sort"
)

type Nutzer struct {
	Name  string
	Alter int
}

func main() {
	nutzer := []Nutzer{{"Ada", 36}, {"Bob", 25}, {"Cem", 41}}
	sort.Slice(nutzer, func(i, j int) bool { return nutzer[i].Alter < nutzer[j].Alter })
	fmt.Println(nutzer) // [{Bob 25} {Ada 36} {Cem 41}]

	slices.SortFunc(nutzer, func(a, b Nutzer) int { return cmp.Compare(b.Name, a.Name) })
	fmt.Println(nutzer) // [{Cem 41} {Bob 25} {Ada 36}]
}

sort.Slice expects a "less than" function on indices, slices.SortFunc (Go 1.21+) a comparison function that returns negative/0/positive. cmp.Compare compares orderable values.

Filter and transform a slice

Data structures#slice#filter#append#deletefunc
Use case: Select and reshape records – Go's replacement for list comprehensions.
package main

import (
	"fmt"
	"slices"
)

func main() {
	zahlen := []int{5, 3, 8, 1, 9}

	var gross []int
	for _, z := range zahlen {
		if z > 3 {
			gross = append(gross, z*2)
		}
	}
	fmt.Println(gross) // [10 6 16 18]

	zahlen = slices.DeleteFunc(zahlen, func(z int) bool { return z%2 == 0 })
	fmt.Println(zahlen) // [5 3 1 9]
}

A simple for loop with append is idiomatic. slices.DeleteFunc removes elements in place and returns the shortened slice – always assign the result.