CodeGym /课程 /Go SELF /Generics 和标准库

Generics 和标准库

Go SELF
第 27 级, 课程 4
可用

1. Context: readability and a small task list

When you first see slices.SortFunc(xs, cmp.Compare[int]), your brain may sometimes react as if you have opened a portal into the world of “complicated words.” In fact, it is the opposite: the standard library tries to pack typical, boring, repetitive loops into short calls with an obvious intention. The idea is not to hide logic, but to remove noise.

In Go, code that reads “left to right” like a story is highly valued: what we want to do, not which exact loop we are going to write for the 27th time in our lives. That is exactly why slices.Delete expresses “delete a range” rather than “perform acrobatics with append and slices.” It is also important to understand the mechanics: if a function changes the length of a slice, it almost always returns a new slice (like append), while if it only changes the order of elements, it often works “in place” and returns nothing (like sorting).

Another useful guideline: the language and the standard library are gradually “aligning” terminology and APIs so that typical code is easier to read. This is also visible in the growth of the generics ecosystem in the stdlib: many everyday operations are now expressed directly with standard calls, without hand-written loops and “reinvented wheels.”

Mini example: a task list as a playground for slices/maps/cmp

To avoid speaking abstractly, we will continue in our educational style: small code examples that come together into one mini application. Let it be a simple in-memory task list: tasks with ID, Title, Done, and tags. We are not touching files, network, or time — only plain data processing, because this is exactly where the slices/maps/cmp packages shine the most.

Let us start with the model and a couple of stubs. We will immediately make Tasks a separate type based on a slice — this is convenient because methods can be added, and the code begins to “read itself” (instead of being a collection of unrelated functions).


package main

type Task struct {
	ID    int
	Title string
	Done  bool
	Tags  []string
}

type Tasks []Task

To make the examples more alive, we will add “demo data” via a function. Yes, this is not a database. Yes, this is not production. But the brain is less distracted.

package main

func sampleTasks() Tasks {
	return Tasks{
		{ID: 3, Title: "buy milk", Done: true, Tags: []string{"home"}},
		{ID: 1, Title: "write a report", Done: false, Tags: []string{"work"}},
		{ID: 2, Title: "read about slices", Done: false, Tags: []string{"study", "go"}},
	}
}

slices + cmp: sorting without hand-written if/else “ladders”

Sorting is one of the most common places where beginners start writing “complex code for a simple result.” It usually looks like a manual sort.Slice, then a field comparison inside, then another comparison, then another... and after 5 minutes you already forget what you were sorting. The slices + cmp combination makes sorting both shorter and more readable: you clearly show by what you are sorting, and you do not drown in details.

The core idea of cmp is simple: the comparator returns -1/0/1, that is, “less / equal / greater.” Such a comparator is convenient to combine and reuse, especially in slices.SortFunc. And most importantly, the code stops looking like a puzzle.

The easiest warm-up: sorting numbers “the human way”

Let us start with a short example that has no structures — just to get used to it visually.

package main

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

func main() {
	nums := []int{10, 3, 7}
	slices.SortFunc(nums, cmp.Compare[int])
	fmt.Println(nums) // [3 7 10]
}

Here it is important to feel the idea: cmp.Compare[int] is a ready-made comparison function for int that you can “pass as an argument.” As a result, the sorting looks almost like a phrase: “sort nums using int comparison.”

Sorting tasks by ID: concise, but without losing meaning

Now we apply the same approach to our task list. Let us write a method that sorts by ID. And let us immediately do an important thing: we will not mutate the original slice; instead, we will make a copy. This is a good habit, because sorting changes the order of elements “in place.”

package main

import (
	"cmp"
	"slices"
)

func (ts Tasks) SortedByID() Tasks {
	cp := slices.Clone(ts)
	slices.SortFunc(cp, func(a, b Task) int {
		return cmp.Compare(a.ID, b.ID)
	})
	return cp
}

Notice that slices.Clone here directly expresses the intention “make a separate copy of the slice.” This is the standard function for slices, just like maps.Clone for maps, and it helps you avoid a “surprise” caused by accidental data mutation.

Sorting by multiple keys: Done → Title → ID

Now for the best part: multi-level sorting usually turns into an “if ladder.” With cmp, it can be done neatly: compare one key, if it is not equal — return, if it is equal — compare the next one.

package main

import (
	"cmp"
	"slices"
)

func (ts Tasks) SortedForOutput() Tasks {
	cp := slices.Clone(ts)

	slices.SortFunc(cp, func(a, b Task) int {
		// false < true, so unfinished (false) tasks come first
		if r := cmp.Compare(a.Done, b.Done); r != 0 {
			return r
		}
		if r := cmp.Compare(a.Title, b.Title); r != 0 {
			return r
		}
		return cmp.Compare(a.ID, b.ID)
	})

	return cp
}

Yes, bool can also be compared via cmp.Compare. And this is one of those moments where a “standard comparator” makes the code clearer: you have a precise comparison order, and it is easy to change, without frying your brain.

maps + slices: stable output and clear operations on map[K]V

Maps in Go are wonderful, but they have one “personality trait”: iteration order via range is not guaranteed. Therefore, any statistical output or grouping via map may end up “dancing” — today one way, tomorrow another. For humans, this is annoying; for tests and scripts, it is outright disastrous. That is why you almost always need stable output: collect keys into a slice, sort them, then print.

The maps package helps you write less manual code when you need to clone, copy, or compare maps. And the slices package helps bring keys into a stable order. It is like two hands of one organism: one gathers the data, the other makes the output predictable.

Tag counters: building map[string]int

Let us count how many times each tag appears across all tasks. This is a typical task: “iterate over the data and increment counters.”

package main

func (ts Tasks) TagStats() map[string]int {
	stats := make(map[string]int)

	for _, t := range ts {
		for _, tag := range t.Tags {
			stats[tag]++
		}
	}
	return stats
}

So far, everything is ordinary. The magic begins at output time.

Stable output: keys → sorting → printing

Stable output means you choose the order yourself. We will do this: take the keys, sort them, then print them.

package main

import (
	"fmt"
	"slices"
)

func printTagStats(stats map[string]int) {
	keys := make([]string, 0, len(stats))
	for k := range stats {
		keys = append(keys, k)
	}
	slices.Sort(keys)

	for _, k := range keys {
		fmt.Printf("%s: %d\n", k, stats[k])
	}
}

There is no maps.Keys here, so that we do not get bogged down in version details and do not get distracted: even such a short loop is perfectly readable. The more important point is this: slices.Sort(keys) shows the intention “sort strings,” and this is easier to read than manually working with the sort package (though that is fine too).

maps.Clone and a “snapshot of state”: when it is useful

Sometimes you need to take a “snapshot” of statistics before changing them. For example, you calculate statistics, then want to “adjust” them (add an artificial tag, merge two tags), while keeping the original for comparison or debugging. In that case, maps.Clone is a simple and readable step.

package main

import "maps"

func copyStats(stats map[string]int) map[string]int {
	return maps.Clone(stats)
}

Here it is important to remember one nuance: maps.Clone makes a shallow copy. If the value is a number or a string, everything is perfect. If the value is a slice or a structure with references, the references are copied, not “the entire universe.” This is not a bug, it is an honest contract.

4. Small generic helpers that complement slices/maps/cmp

It is very easy to slip into “let us write our own mini-stdlib”: map, Filter, Reduce, FlatMap, Distinct, and in a day your project will look like a suspicious parody of functional languages. But there is another way: write 1–2 small generic helpers that really cover a repetitive pattern, and then combine them with the standard slices/maps/cmp.

The key principle: if the standard library already expresses the intention — use it. If you repeat the same loop in 3–4 places and each time are afraid of making a mistake — carefully extract it into a generic function. This is the “golden mean” where generics help, but do not take over the project.

Filter[T]: filtering a slice without losing the type

Filtering is a super common operation. Yes, you can write the loop every time. But Filter as a utility is usually short and clear. We will make a version that returns a new slice and tries to be memory-friendly (preallocate capacity).

package main

func Filter[T any](xs []T, keep func(T) bool) []T {
	out := make([]T, 0, len(xs))
	for _, x := range xs {
		if keep(x) {
			out = append(out, x)
		}
	}
	return out
}

Now you can filter tasks by completion status — and the Task type is not lost, unlike the “universal” approach via []any.

package main

func (ts Tasks) Undone() Tasks {
	return Filter(ts, func(t Task) bool {
		return !t.Done
	})
}

GroupBy[K comparable, T any]: grouping into map[K][]T

Grouping is the second typical pattern. And it maps very well to generics: the key must be comparable (because it is a map key), the element can be anything.

package main

func GroupBy[T any, K comparable](xs []T, key func(T) K) map[K][]T {
	groups := make(map[K][]T)
	for _, x := range xs {
		k := key(x)
		groups[k] = append(groups[k], x)
	}
	return groups
}

For example, let us group tasks by the Done status:

package main

func (ts Tasks) GroupByDone() map[bool]Tasks {
	raw := GroupBy(ts, func(t Task) bool { return t.Done })

	// a small “cleanup” so we return map[bool]Tasks instead of map[bool][]Task
	out := make(map[bool]Tasks, len(raw))
	for k, v := range raw {
		out[k] = Tasks(v)
	}
	return out
}

Yes, there is a small loop here to “clean up” the type. It is not scary: in return, you get to work with Tasks as a “slice with methods.”

5. Putting it all together: a short main that reads like a scenario

The final goal of this lecture is for the code at the usage site to read in simple steps. Not “we do some clever trick here,” but “we take tasks, filter, sort, build statistics, print.” When main turns into such a “sequence of actions,” the project becomes easier to maintain: you quickly find where things happen, and you are less afraid to change the code.

Now let us assemble a demo main that uses our Tasks type, the package functions slices/maps/cmp, and a couple of small generic helpers. No magic, just composition — like LEGO, but without losing pieces under the sofa.

Printing tasks in a stable order

Let us make a small printing function so the examples are complete. Printing is not the goal of the lecture, but it lets us see the result.

package main

import "fmt"

func printTasks(ts Tasks) {
	for _, t := range ts {
		fmt.Printf("#%d done=%v title=%q tags=%v\n", t.ID, t.Done, t.Title, t.Tags)
	}
}

Final main: minimum code, maximum intention

Now for the main scenario.

package main

import "fmt"

func main() {
	tasks := sampleTasks()

	fmt.Println("All (sorted for output):")
	printTasks(tasks.SortedForOutput())

	fmt.Println("\nUndone only (sorted by id):")
	printTasks(tasks.Undone().SortedByID())

	fmt.Println("\nTag stats:")
	printTagStats(tasks.TagStats())
}

This main is important not because of its output, but because of how it reads: every expression looks like a “phrase.” That is exactly why we combine standard generics packages with a few of our own small utilities.

6. Typical mistakes

Mistake #1: expecting sorting to return a new slice.
This is a common trap from the world of “functional thinking”: it seems that any operation should return a result. In Go, sorting usually rearranges elements “in place,” meaning it modifies the same slice. Therefore, if you want to preserve the original order, first make a copy with slices.Clone, and then sort the copy. The “copy → sort” model is especially important in code where the same list is used in different views.

Mistake #2: forgetting assignment after operations that change length.
There are functions (both in the standard library and your own) that change a slice’s length. By contract, such operations must return a new slice (like append or slices.Delete), because the length may have changed and the underlying array may even have been reallocated. If you call such a function and do not assign the result back to a variable, your code will “politely do nothing,” and you will end up debugging emptiness.

Mistake #3: making Filter/GroupBy/Sort/Whatever “for all cases” and turning the project into a library of abstractions.
Generics are very tempting: “oh, I can extract everything.” But the price is complex signatures, unclear names, and code that is hard for beginners to debug (and for you a month later). A good practice is: first use slices/maps/cmp where they directly express the intention, and only then add 1–2 small generic helpers when you really see a repeating pattern.

Mistake #4: unstable output from map and “random” results on the screen.
Beginners often think: “well, I added keys in the order A, B, C, so range over map should also be A, B, C.” It will not. The iteration order of map is not guaranteed, and that is normal. If you print something for a user or compare output in tests, stabilize the order: collect keys into a slice, sort with slices.Sort, then iterate over the keys. This is almost always two extra lines that save hours of debugging.

Mistake #5: confusing “short” with “clear.”
Sometimes you can write one line that does everything at once. But if that line cannot be explained quickly to your neighbor (or to yourself a week later), you have not won. The combination of generics and standard packages should shorten code by removing noise, not by turning logic into a riddle. If you have to stare at an expression for a long time, it is better to split it into a couple of variables with good names.

1
任务
Go SELF, 第 27 级, 课程 4
已锁定
按编号升序排列的仓库
按编号升序排列的仓库
1
任务
Go SELF, 第 27 级, 课程 4
已锁定
词频报告
词频报告
1
任务
Go SELF, 第 27 级, 课程 4
已锁定
工单副本
工单副本
1
任务
Go SELF, 第 27 级, 课程 4
已锁定
按组统计的购物篮
按组统计的购物篮
1
调查/小测验
Generics第 27 级,课程 4
不可用
Generics
Generics
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION