NASutils Knowledge BaseUnofficialPolski

Go · lesson 13 of 30 · Data, functions and the command lineCount with a map

A map finds a value by its name. ok tells you whether the name is there.

Programming on the NAS › Go in 30 lessons

13-maps.go Download 13-maps.go

package main

import (
	"fmt"
	"maps"
	"slices"
)

func main() {
	count := map[string]int{}
	for _, level := range []string{"INFO", "WARN", "INFO", "ERROR", "INFO"} {
		count[level]++
	}

	// a map has no order, so sort its keys before you print
	for _, level := range slices.Sorted(maps.Keys(count)) {
		fmt.Println(level, count[level])
	}

	if n, ok := count["DEBUG"]; ok {
		fmt.Println("DEBUG", n)
	} else {
		fmt.Println("no DEBUG lines")
	}
	delete(count, "INFO")
	fmt.Println(len(count), "levels left")
}

Terminal

$ ./13-maps
ERROR 1
INFO 3
WARN 1
no DEBUG lines
2 levels left

Exercise

Print the levels by their count, highest first.

TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.