CodeGym /행동 /Go SELF /Using map[T]struct{} and counters for sets

Using map[T]struct{} and counters for sets

Go SELF
레벨 15, 레슨 4
사용 가능

1. Two map patterns: set and counter

When you first see a map, you want to use it literally: “key → value.” But in real code, a map often serves as a universal accounting mechanism: it can quickly answer the questions “have I seen this before?” and “how many times has this occurred?” That is why in Go, many things that are separate structures in other languages are built on maps.

Imagine you are writing a small console utility: the user enters words/tags, and the program must (a) show a list of unique values and (b) count frequencies. Of course, you could store everything in a slice and linearly search for a match each time, but then the program will start slowing down already at a few hundred elements. A map solves both tasks elegantly, and today we will learn to read and write such code with confidence.

For orientation — a mini table of “what we want to get”:

Task What needs to be stored What the type looks like in Go How to “check” it
Set of unique values presence fact
map[string]struct{}
_, ok := set[x]
Frequencies/counters number of repetitions
map[string]int
counts[x]
or
v, ok := counts[x]

2. A set: map[T]struct{}

If you come from languages that have a built-in Set, Go may at first seem “stingy”: why do I have to do everything myself again? In fact, Go is not stingy, but minimalist: the basic map is so convenient that it makes an excellent set without magic and without new rules. You get a data structure that you already know how to create, iterate over, and clear.

The idea of a set is simple: we do not need to store a “value”, we only need the fact: “the element is present.” So as the value (V) we can use a type that stores nothing. Go has such a type: the empty structure struct{}. It has no fields, and it is often used as a marker for “just because”.

Minimal set example

package main

import "fmt"

func main() {
	set := make(map[string]struct{})
	set["go"] = struct{}{}
	set["map"] = struct{}{}

	fmt.Println(len(set)) // 2
}

Here struct{}{} is an “empty value”. We put it there only because the map requires a value, but the meaning is carried by the key.

Set operations: add/has/remove/size

When you see map[string]struct{} in someone else’s code, do not try to search for “what is stored there.” It stores “nothing”, and that is the whole point. Think of it as a “present/absent” table. Then set operations read almost like English: “add”, “check”, “delete”, “count”.

Here is a compact set of operations that you will write all the time:

package main

import "fmt"

func main() {
	tags := make(map[string]struct{})

	tags["urgent"] = struct{}{}     // add
	_, ok := tags["urgent"]         // has
	delete(tags, "urgent")          // remove
	fmt.Println(ok, len(tags))      // true 0
}

Note: delete(tags, "urgent") is safe even if the key does not exist — it will simply do nothing. That is pure “zen”: fewer checks — fewer places to make mistakes.

Why not map[string]bool

A natural beginner question: “Why not make a set as map[string]bool?” You can store true/false. You can. But it is less expressive and sometimes more dangerous for reading. The main problem: false is an ordinary value, and it is hard to distinguish from the situation “the key is missing.”

Look at the example: it compiles, but logically it may confuse you a week later (or even in two hours).

package main

import "fmt"

func main() {
	m := map[string]bool{"featureA": false}

	fmt.Println(m["featureA"]) // false (key exists, value false)
	fmt.Println(m["featureB"]) // false (key does not exist, zero value)
}

Both times it prints false, but the meaning is different. Of course, you can use the ok idiom here too, but then the question arises: why use bool at all? If we are building a set, then map[string]struct{} says to the reader directly: “I am a set,” and reduces the chance that someone will write if m[x] { ... } and accidentally confuse “no key” with “key exists, but false”.

3. Counters and frequencies: map[string]int

After sets, the second most useful map pattern is a counter. It is so common that it appears in algorithm problems, log processing, analytics, data import, and even the most ordinary CLI programs. And here what we already know helps us: if a key is missing, reading returns the zero value.

For int, the zero value is 0. That means the statement counts[word]++ works even if word appears for the first time: first 0 is taken, then 1 is added, then it is written back into the map.

Mini frequency example

package main

import "fmt"

func main() {
	words := []string{"go", "map", "go"}

	counts := make(map[string]int)
	for _, w := range words {
		counts[w]++
	}

	fmt.Println(counts["go"])   // 2
	fmt.Println(counts["java"]) // 0
}

And here it is important not to make the wrong conclusion: 0 does not mean “the key definitely existed.” It means “either there was no key, or the value is 0.” If you need to distinguish these cases, we return to the ok idiom.

When you really need ok

In a simple frequency counter, 0 is almost always fine. But there are situations where 0 is a real value. For example, you store the “current bonus balance”, and it can become zero after spending. Or you store the “number of attempts left”, and 0 means “the key exists, but there are no attempts left.” In such cases it is useful to distinguish the absence of a key.

A short example of the ok idiom for map[string]int:

package main

import "fmt"

func main() {
	counts := map[string]int{"go": 0}

	v1, ok1 := counts["go"]
	v2, ok2 := counts["java"]

	fmt.Println(v1, ok1) // 0 true
	fmt.Println(v2, ok2) // 0 false
}

This check is especially helpful when you write code to “delete a key if the value became 0.” It is not a mandatory rule, but sometimes it makes the data cleaner: fewer keys with zero values.

4. Example: a mini TagStats utility

Now we will put everything together in one small console program. It will be simple (we still do not know how to read full lines with spaces in a convenient way, so we read “tokens”), but very honest: the user enters n, then n tags. The program outputs the number of unique tags and the frequency of each tag.

Reading input into []string

First, read the input into []string. Notice that we preallocate slice capacity — you have already done this in the topic about make and append.

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)

	tags := make([]string, 0, n)
	for i := 0; i < n; i++ {
		var t string
		fmt.Scan(&t)
		tags = append(tags, t)
	}

	fmt.Println(tags) // example: [go map go]
}

Building a set and a counter on top of the same data

Now, on top of this data, we build both a set of unique tags and a counter:

unique := make(map[string]struct{})
counts := make(map[string]int)

for _, t := range tags {
	unique[t] = struct{}{}
	counts[t]++
}

fmt.Println("unique:", len(unique)) // unique: 2

So far we have printed only the number of unique values. But we also want to print the frequencies.

Stable output: sort the keys

The map order is not guaranteed, so for a “beautiful and repeatable” result we collect the keys and sort them.

package main

import (
	"fmt"
	"sort"
)

func main() {
	counts := map[string]int{"go": 2, "map": 1}

	keys := make([]string, 0, len(counts))
	for k := range counts {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	for _, k := range keys {
		fmt.Println(k, counts[k])
	}
	// go 2
	// map 1
}

If you put it all together, you get a “small application” that can really be expanded in later topics, for example, by storing “tasks” and “task tags.” For now, without structs, we are limited in data modeling, but we can already do useful analytics on top of strings.

Data flow diagram

A small data flow diagram (so the brain does not pretend it is a nil-map):

flowchart TD
    A[Read n tags] --> B[For each tag t]
    B --> C["unique[t] = struct{}{}"]
    B --> D["counts[t]++"]
    C --> E["Unique = len(unique)"]
    D --> F[Keys counts -> sort -> print]

5. Key limitations: what you can put into map and set

Sometimes it seems that map is a magical bag where you can put any keys: strings, numbers, anything. But a map has an important limitation: the key must be something that can be compared and “hashed.” In human language, that means: the key must be comparable (support ==/!= without surprises). That is why, for example, slices cannot be used as keys.

There are even scenarios where a key seemingly allows different types, and then, when you try to use an incomparable type, you can get a crash with a message like "hash of unhashable type []int". Within our course, it is enough to remember a simple rule: for the sets and counters from today’s lecture, use string or int as keys — and you will have a calm life without unexpected panics.

6. Typical mistakes

Mistake #1: making a set as map[string]bool and checking it with if set[x] { ... }.
Such code sometimes “works,” but it is hard to read and easy to break if someone starts storing false as a meaningful value. If you really want a set, map[string]struct{} expresses the intention better: element presence is checked via _, ok := set[x], and this does not get confused with values.

Mistake #2: trying to check for a missing key in a counter with if counts[k] == 0.
For frequencies this is often acceptable, but logically it means not “the key is absent,” but “the value is currently 0.” If you need to distinguish “never existed” and “existed, but became 0,” use v, ok := counts[k]. This same rule also saves you in situations where you want to delete keys with zero and are not sure whether they were present at all.

Mistake #3: forgetting make and writing into a nil-map.
var set map[string]struct{} looks fine, and reading from such a map will not crash. But as soon as you do set["x"] = struct{}{}, the program will crash at runtime. So the practical rule is simple: if you are going to add elements, create the map with make(...) before the first write.

Mistake #4: expecting a “pretty order” when printing a counter with for k, v := range counts.
The order of map iteration is not a contract; it can change. Because of this, tests, output comparison, and even just “checking by eye” become painful. If you output results to the user and want stability, use the familiar recipe: collect keys into a slice, sort them, print by keys.

Mistake #5: storing in a set something other than what you check.
This sounds funny, but it happens often: you add strings to a set in one format (for example, with different case: "Go" and "go"), but you check in another, and it “somehow cannot be found.” If you are building a set of strings, normalize them in advance (at least with strings.ToLower) and only then put them into map[string]struct{}.

1
과제
Go SELF, 레벨 15, 레슨 4
잠금
고유한 명령어
고유한 명령어
1
과제
Go SELF, 레벨 15, 레슨 4
잠금
접근 확인
접근 확인
1
과제
Go SELF, 레벨 15, 레슨 4
잠금
알파벳 빈도수 계산기
알파벳 빈도수 계산기
1
과제
Go SELF, 레벨 15, 레슨 4
잠금
온라인과 리더
온라인과 리더
1
설문조사/퀴즈
Map, 레벨 15, 레슨 4
사용 불가능
Map
Map: ok-idioma, set-pattern
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION