Generics and generic methods: when you don't need them
Type parameters and constraints, ~ and cmp.Ordered, generic methods in Go 1.27 and their limit, and three smells of needless generic code.
🌐 Oʻzbekcha · Русский · English
Lesson GO-1.17 · Go: 0 → Guru · ▶️ video coming soon · 💻 GitHub
This is the full written version of the video lesson: you can learn from it without watching (or hearing) the video. The video itself is in Uzbek.
What you will learn
The official Go FAQ still has this sentence today: “We do not anticipate that Go will ever add generic methods.” But Go 1.27 added them. The same file is a syntax error in Go 1.26 and runs in Go 1.27. There is only one condition, and that same FAQ still calls this condition “unacceptable”. What is the condition, and why did the Go team choose exactly it?
The one idea: a type parameter is for writing the same code for different types once; an interface is for behaviour. In Go 1.27 methods became generic too, but a generic method implements no interface.
By the end of the lesson you will:
- write type parameters and constraints, and know why
~is needed and howcmp.Orderedis built; - write a Go 1.27 generic method and predict when it does not compile (
go.mod, interfaces); - recognise needless generic code by three smells and turn it into an interface or a plain function;
- check the claim “generics are faster than interfaces” with a benchmark,
-gcflags=-mandgo tool nm.
Today’s three core new words:
| Word | Plain meaning | English term |
|---|---|---|
| type parameter | a type name in square brackets in a function or type declaration (T); the call decides which type it is | type parameter |
| constraint | an interface that limits which types a type parameter can be (cmp.Ordered) | constraint |
| generic method | a method that declares its own type parameter: func (r Royxat[T]) Aylantir[U any](…) (Go 1.27+) | generic method |
Two helper words also appear: type inference (the compiler finds the type from the arguments) and
instantiation (a concrete type is put in place of T). We see both in the first program.
Before you start
- GO-1.12 · Metodlar: value receiver yoki pointer receiver?: methods, receivers, method values
(
f := b.Jami). Generic methods are built on top of these. - GO-1.13 · Interface’lar: nil nega nil’ga teng emas?: an interface is implemented without
implements,any(the empty interface), type assertionx.(T), type switch. A constraint is an interface too. - GO-1.16 · go.mod’dagi bitta qator dasturingiz xulqini oʻzgartiradi: the
goline sets the language version (-lang),GOTOOLCHAIN=localandGOTOOLCHAIN=go1.27.4. - GO-1.03 · Konstanta va iota: JS const emas, time.Sleep(2) va enum oʻrtasidagi jim bug: untyped constants and the default type. The pause question relies on this.
- GO-1.06 · Funksiyalar: ikki qiymat qaytarish, closure va variadic: functions as values (a
func(T) Uparameter). - GO-1.07 · Taxmin qilmang, oʻlchang: birinchi test va benchmark:
go test -bench,b.Loop, inlining. - GO-1.08 · Slice’lar: append tuzogʻi va eskirgan 1024 qoidasi:
make,append,len. - This lesson needs Go 1.27. The course folder
lessons/017-genericsis a separate module: itsgo.modhasgo 1.27andtoolchain go1.27.4. Even if your computer has an older Go, the defaultGOTOOLCHAIN=autodownloads go1.27.4 by itself (GO-1.16). Open a terminal in this folder; every command runs from there.cd eski && …first moves into theeskifolder, then runs the command. - The results come from
go1.27.4 linux/amd64, and fromgo1.26.8for the “before”.
First, a question about the previous lesson. Your computer has Go 1.27.4, and the module’s go.mod has go 1.26.
The code uses syntax that was added only in Go 1.27. What does go build do?
Answer
A compile error. Even though the compiler is 1.27.4, it compiles the module with -lang=go1.26, taken from the
go line, and rejects syntax that Go 1.26 does not have. The message ends with
(-lang was set to go1.26; check go.mod). Today we see exactly this with a generic method.
Puzzle: the FAQ says “never”, Go 1.27 runs it
The program in the hook/ folder. You don’t need to understand every line yet: we open up [T any] and [U any]
in the next sections.
// hook: Go 1.27 dagi generic metod. Xuddi shu fayl ../eski da (go 1.26) kompilyatsiya boʻlmaydi.
// go run ./hook
package main
import "fmt"
type Royxat[T any] []T
// Aylantir har bir elementga f ni qoʻllaydi.
// U — metodning oʻz type parametri: Go 1.27 dan beri mumkin.
func (r Royxat[T]) Aylantir[U any](f func(T) U) Royxat[U] {
natija := make(Royxat[U], len(r))
for i, x := range r {
natija[i] = f(x)
}
return natija
}
func main() {
summalar := Royxat[int64]{150000, 99000, 42000}
matn := summalar.Aylantir(func(s int64) string {
return fmt.Sprintf("%d soʻm", s)
})
fmt.Println(matn)
}| Line | Code | What it does |
|---|---|---|
| 7 | type Royxat[T any] []T | Royxat (“list”) is a slice type whose elements have type T; T is a type parameter, any means any type |
| 11 | func (r Royxat[T]) Aylantir[U any](f func(T) U) Royxat[U] | its own square brackets after the method name: U is the method’s own type parameter. f turns each T into a U; the result is a Royxat[U] |
| 12 | natija := make(Royxat[U], len(r)) | natija (“result”): a new slice as long as r, with U elements |
| 13–15 | for i, x := range r { natija[i] = f(x) } | applies f to each element |
| 20 | Royxat[int64]{150000, 99000, 42000} | int64 in place of T: summalar (“amounts”), order totals in soʻm |
| 21–23 | summalar.Aylantir(func(s int64) string {…}) | U = string: each amount becomes text |
| 24 | fmt.Println(matn) | prints the slice as [a b c] |
In TypeScript this is ordinary: the map<U>(f: (x: T) => U): U[] method of Array<T> is exactly such a generic
method. In Go, before 1.27, you could not write a method like this.
The eski/ folder (“old”) holds exactly this file (diff prints nothing, so the files are the same):
$ diff hook/main.go eski/main.goThe only difference is in eski/go.mod: it says go 1.26. First we build it with the old Go 1.26.8 installed on
the computer. GOTOOLCHAIN=local means: don’t download another Go, use the installed one; -o /dev/null means:
don’t write the binary anywhere.
Think: what does Go 1.26.8 do with this file?
A) builds it, it runs · B) builds it, but with a warning · C) compile error
Answer
C. In the Go 1.26 grammar a method name cannot be followed by square brackets. The parser stops when it reaches
[U any] on line 11. If you chose “B”: Go has no “build with a warning”; code either compiles or it doesn’t.
$ cd eski && GOTOOLCHAIN=local go version && GOTOOLCHAIN=local go build -o /dev/null .
go version go1.26.8 linux/amd64
# eski
./main.go:11:28: syntax error: method must have no type parameters11:28 is line 11, column 28, the start of [U any]. Now the same code with Go 1.27.4 (hook/ has go 1.27 in
its go.mod):
$ go version && go run ./hook
go version go1.27.4 linux/amd64
[150000 soʻm 99000 soʻm 42000 soʻm]Go 1.27 release notes: “Go 1.27 now supports generic methods: a method declaration may declare its own type
parameters”. This method declares its own type parameter called U. There is only one condition. We see it in the
“Limit” section.
The plan of the lesson: first type parameters and constraints, then generic methods and their limit, and at the end the most important question: when is generic code needless?
Type parameter: same code, different type
The program in katta/ (“bigger”) has two functions. One returns the bigger of two integers, the other the bigger
of two strings. The code is the same; only the type differs.
// katta: bir xil kod ikki marta, faqat tur boshqa → bitta generic funksiya.
// go run ./katta
package main
import (
"cmp"
"fmt"
)
func KattaInt(a, b int) int {
if a > b {
return a
}
return b
}
func KattaString(a, b string) string {
if a > b {
return a
}
return b
}
// T — type parameter, cmp.Ordered — uning constraint'i.
func Katta[T cmp.Ordered](a, b T) T {
if a > b {
return a
}
return b
}
func main() {
fmt.Println(Katta(3, 7), Katta(1.5, 0.5), Katta("olma", "nok"))
fmt.Println(Katta[int64](150000, 99000))
fmt.Println(KattaInt(3, 7), KattaString("olma", "nok"))
}| Line | Code | What it does |
|---|---|---|
| 6 | "cmp" | the standard library cmp package (Go 1.21+): cmp.Ordered lives here |
| 10–15 | func KattaInt(a, b int) int | for int: a if a > b, otherwise b |
| 17–22 | func KattaString(a, b string) string | exactly the same code, only for string (strings compare in alphabetical order) |
| 25 | func Katta[T cmp.Ordered](a, b T) T | T in square brackets is the type parameter; cmp.Ordered is the constraint: T can only be a type that compares with < and > |
| 26–29 | if a > b { return a }; return b | the body is the same as in the two above |
| 33 | Katta(3, 7), Katta(1.5, 0.5), Katta("olma", "nok") | three calls, three types, we wrote no type (olma “apple”, nok “pear”) |
| 34 | Katta[int64](150000, 99000) | we gave the type ourselves in square brackets |
| 35 | KattaInt(3, 7), KattaString("olma", "nok") | the two old functions, for comparison |
The same function in other languages (both were run: TypeScript 5.9.3, Python 3.13):
TypeScript: function katta<T extends number | string>(a: T, b: T): T { return a > b ? a : b; }
Python 3.12+: def katta[T: (int, str)](a: T, b: T) -> T: return a if a > b else b
Go: func Katta[T cmp.Ordered](a, b T) T { if a > b { return a }; return b }TS’s <T extends …> is Go’s [T constraint]. The difference is at run time: TS and Python use types only for
checking. When the program runs, one JS or Python function is left and any value gets through. The Go compiler
checks the type itself and produces machine code: Katta(3, "nok") does not compile at all. PHP has no generics in
the language itself: PHPStan and Psalm check @template annotations.
When should you write a type parameter? Ian Lance Taylor, When To Use Generics (Go blog, 2022): “avoid type
parameters until you notice that you are about to write the exact same code multiple times”. That is exactly our
case: KattaInt and KattaString.
Think: what is the first line of go run ./katta?
A) 7 1.5 olma · B) 7 1.5 nok · C) compile error: no type was given to Katta
Answer
A. "olma" is bigger than "nok", because strings compare byte by byte and o (111) comes after n (110).
If you chose “B”, you thought string length is compared. If you chose “C”: you don’t have to write the type, the
compiler finds it from the arguments.
$ go run ./katta
7 1.5 olma
150000
7 olmaKatta worked with an integer, a float and a string, and we never wrote the type. The compiler found T from the
arguments by itself: int from 3 and 7, float64 from 1.5. This is called type inference. On the second
line we gave the type ourselves as Katta[int64]. In both cases the compiler puts a concrete type in place of T:
this is called instantiation. The Go specification: “A generic function, method, or type is instantiated by
substituting type arguments for the type parameters”.
| Call | Where T comes from | T | Result |
|---|---|---|---|
Katta(3, 7) | type inference | int | 7 |
Katta(1.5, 0.5) | type inference | float64 | 1.5 |
Katta("olma", "nok") | type inference | string | olma |
Katta[int64](150000, 99000) | we gave it | int64 | 150000 |
One note: since Go 1.21 the language itself has a max function. Its signature is exactly this:
$ go doc builtin.max | sed -n 3p
func max[T cmp.Ordered](x T, y ...T) TKatta is only an example. Before writing a generic, look for a ready one: max, min, the slices and maps
packages.
A constraint is an interface
A constraint is really an ordinary interface. The only thing is that besides methods it can also have a list of types. Such a list defines the interface’s type set, the set of types it allows.
// cheklov: oʻz constraint'imiz. ~int64 — "asosiy turi int64 boʻlgan har qanday tur".
// go run ./cheklov
package main
import "fmt"
type Son interface {
~int64 | ~float64
}
type Ball int64 // asosiy (underlying) turi int64
func Jami[T Son](xs []T) T {
var s T
for _, x := range xs {
s += x
}
return s
}
func main() {
fmt.Println(Jami([]Ball{90, 85, 70}))
fmt.Println(Jami([]float64{1.5, 2.25}))
}| Line | Code | What it does |
|---|---|---|
| 7–9 | type Son interface { ~int64 | ~float64 } | Son (“number”) is a constraint: two types, | means “or”. No methods, only types |
| 8 | ~ (tilde) | “every type whose underlying type is this one” (see below) |
| 11 | type Ball int64 | Ball (“score”) is a new named type whose underlying type is int64 |
| 13 | func Jami[T Son](xs []T) T | Jami (“total”): T can only be one of the types in Son |
| 14 | var s T | the zero value of T: 0 |
| 16 | s += x | allowed, because every type in Son knows + |
| 22 | Jami([]Ball{90, 85, 70}) | T = Ball |
| 23 | Jami([]float64{1.5, 2.25}) | T = float64 |
It looks like TS’s T extends number | string. But in Go, type Ball int64 is not an alias of int64; it is a
separate type (like type Status int in GO-1.03). That is why ~ is needed. The Go
specification: “The type set of a term of the form ~T is the set of all types whose underlying type is T”.
$ go run ./cheklov
245
3.7590 + 85 + 70 = 245, 1.5 + 2.25 = 3.75. Now we remove the ~ sign. tildesiz/main.go (“without tilde”) is the same
everywhere else; only lines 7–9 differ:
type Son interface {
int64 | float64
}$ go build -o /dev/null ./tildesiz
# generics/tildesiz
tildesiz/main.go:22:18: Ball does not satisfy Son (possibly missing ~ for int64 in Son)We read the error: line 22, Jami([]Ball{…}). Ball does not satisfy Son. In brackets the compiler even gives a
hint: possibly missing ~ for int64 in Son. Without ~, the type set of Son is just two types: int64 and
float64. Ball is not among them.
Son | int64 | Ball (underlying type int64) | float64 |
|---|---|---|---|
~int64 | ~float64 | yes | yes | yes |
int64 | float64 | yes | no | yes |
cmp.Ordered in the standard library is written the same way:
$ sed -n 18,23p $(go env GOROOT)/src/cmp/cmp.go
type Ordered interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
~float32 | ~float64 |
~string
}Every type has a ~ in front of it, so cmp.Ordered also works with the types you create: Katta(Ball(90), Ball(85)) compiles.
Generic methods (Go 1.27)
The Royxat type is generic; its elements have type T. Since Go 1.18 generic types have methods, but those
methods can only use the T from the receiver. What if a new type is needed? royxat/ is the Go 1.18–1.26 way:
// royxat: Go 1.18–1.26 usuli. Metod faqat receiver'dagi T ni ishlata oladi,
// yangi tur (U) kerak boʻlsa — paket darajasidagi funksiya.
// go run ./royxat
package main
import "fmt"
type Royxat[T any] []T
// Filtr: faqat T kerak — metod boʻla oladi (Go 1.18 dan beri).
func (r Royxat[T]) Filtr(ok func(T) bool) Royxat[T] {
var natija Royxat[T]
for _, x := range r {
if ok(x) {
natija = append(natija, x)
}
}
return natija
}
// Aylantir: yangi U kerak — 1.27 gacha faqat funksiya.
func Aylantir[T, U any](r Royxat[T], f func(T) U) Royxat[U] {
natija := make(Royxat[U], len(r))
for i, x := range r {
natija[i] = f(x)
}
return natija
}
func main() {
r := Royxat[int64]{150000, 99000, 42000}
fmt.Println(Aylantir(r.Filtr(katta), somda))
}
func katta(s int64) bool { return s > 50000 }
func somda(s int64) string { return fmt.Sprintf("%d soʻm", s) }| Line | Code | What it does |
|---|---|---|
| 8 | type Royxat[T any] []T | a generic type: its elements are T |
| 11 | func (r Royxat[T]) Filtr(ok func(T) bool) Royxat[T] | Filtr (“filter”) needs no new type, only the receiver’s T: so it is a method |
| 12–18 | var natija …; if ok(x) { natija = append(natija, x) } | collects the elements for which ok returns true |
| 22 | func Aylantir[T, U any](r Royxat[T], f func(T) U) Royxat[U] | Aylantir (“convert”) returns a new type U: before 1.27 it could only be a package-level function |
| 31 | r := Royxat[int64]{…} | three amounts |
| 32 | Aylantir(r.Filtr(katta), somda) | first r.Filtr(katta), then its result goes into Aylantir |
| 35 | func katta(s int64) bool | amounts bigger than 50,000 soʻm |
| 36 | func somda(s int64) string | somda (“in soʻm”) turns an amount into the text "… soʻm" |
Before 1.27 the Go FAQ recommended exactly this: “use top-level functions with type parameters”. You read the call
on line 32 from the inside out: first the inner r.Filtr(katta), then the outer Aylantir. Python’s
map(somda, filter(katta, r)) reads the same way.
Think: what does go run ./royxat print?
A) [150000 soʻm 99000 soʻm 42000 soʻm] · B) [150000 soʻm 99000 soʻm] · C) [42000 soʻm]
Answer
B. katta keeps the amounts bigger than 50,000: 150,000 and 99,000. 42,000 does not pass the filter. If you
chose “A”, you ignored Filtr. If you chose “C”, you read katta backwards.
$ go run ./royxat
[150000 soʻm 99000 soʻm]In Go 1.27 Aylantir can be a method. zanjir/ (“chain”) is the same as royxat/ everywhere else:
// zanjir: Go 1.27 usuli. Aylantir endi metod — chaqiruvlar chapdan oʻngga oʻqiladi.
// go run ./zanjir
package main
import "fmt"
type Royxat[T any] []T
func (r Royxat[T]) Filtr(ok func(T) bool) Royxat[T] {
var natija Royxat[T]
for _, x := range r {
if ok(x) {
natija = append(natija, x)
}
}
return natija
}
// U — metodning oʻz type parametri (Go 1.27).
func (r Royxat[T]) Aylantir[U any](f func(T) U) Royxat[U] {
natija := make(Royxat[U], len(r))
for i, x := range r {
natija[i] = f(x)
}
return natija
}
func main() {
r := Royxat[int64]{150000, 99000, 42000}
fmt.Println(r.Filtr(katta).Aylantir(somda))
}
func katta(s int64) bool { return s > 50000 }
func somda(s int64) string { return fmt.Sprintf("%d soʻm", s) }The new lines:
| Line | Code | What it does |
|---|---|---|
| 20 | func (r Royxat[T]) Aylantir[U any](f func(T) U) Royxat[U] | T comes from the receiver, and the U in square brackets belongs to the method itself: this is a generic method |
| 30 | r.Filtr(katta).Aylantir(somda) | left to right: first filter, then convert. U = string, found by type inference |
$ go run ./zanjir
[150000 soʻm 99000 soʻm]The result is the same. It now looks very much like JS’s r.filter(katta).map(somda). The author of the proposal,
Robert Griesemer (golang/go#77273), gives two reasons. The first is reading: “x.a().b().c() may naturally be read
left to right, whereas c(b(a(x))) is evaluated inside out”. The second: “A method is a function associated with a
type”: the function is tied to its type and lives in that type’s namespace.
| Go 1.18–1.26 | Go 1.27 | |
|---|---|---|
method using the receiver’s T (Filtr) | yes | yes |
method with its own type parameter (Aylantir[U]) | no: syntax error | yes: generic method |
| call | Aylantir(r.Filtr(katta), somda) | r.Filtr(katta).Aylantir(somda) |
The go.mod condition: a new Go is not enough
Installing a new Go is not enough. We build the eski/ folder with Go 1.27.4, but its go.mod file says:
$ grep '^go ' eski/go.mod
go 1.26GOTOOLCHAIN=go1.27.4 means: use exactly this Go version (GO-1.16):
$ cd eski && GOTOOLCHAIN=go1.27.4 go build -o /dev/null .
# eski
./main.go:11:29: generic method requires go1.27 or later (-lang was set to go1.26; check go.mod)generic method requires go1.27 or later. In brackets is the reason: -lang was set to go1.26, check go.mod. The
compiler is 1.27.4, but as we saw in GO-1.16, the go line sets the language version.
| Go | go line in go.mod | Result |
|---|---|---|
| 1.26.8 | go 1.26 | syntax error: method must have no type parameters |
| 1.27.4 | go 1.26 | generic method requires go1.27 or later |
| 1.27.4 | go 1.27 (hook/) | runs |
The practical conclusion: if you write a generic method in your library, its go.mod becomes go 1.27. Your users
also have to move to Go 1.27.
In the standard library: rand.N
The standard library got such a method too: (*Rand).N in the math/rand/v2 package.
$ sed -n 210,213p $(go env GOROOT)/src/math/rand/v2/rand.go
// N returns a pseudo-random number in the half-open interval [0,n).
// The type parameter Int can be any integer type.
// It panics if n <= 0.
func (r *Rand) N[Int intType](n Int) Int {Its type parameter called Int takes any integer type: the intType constraint is ~int | ~int8 | … | ~uintptr
(lines 340–343 of the same file). In the go1.27.4 source, outside tests, this is the only generic method (checked
with the grep command in the course README).
// randn: standart kutubxonadagi birinchi generic metod — (*rand.Rand).N (Go 1.27).
// go run ./randn
package main
import (
"fmt"
"math/rand/v2"
"time"
)
func main() {
r := rand.New(rand.NewPCG(1, 2)) // doimiy seed: natija har safar bir xil
fmt.Println(r.N(10)) // int
fmt.Println(r.N(int64(150000))) // int64
fmt.Println(r.N(3 * time.Second)) // time.Duration
fmt.Printf("%T\n", r.N[uint8]) // aniq tur bilan instantiate
}| Line | Code | What it does |
|---|---|---|
| 12 | rand.New(rand.NewPCG(1, 2)) | a random number generator with a fixed seed: the result is the same every time |
| 13 | r.N(10) | Int = int: one number from 0…9 |
| 14 | r.N(int64(150000)) | Int = int64 |
| 15 | r.N(3 * time.Second) | Int = time.Duration (underlying type int64, so it is in ~int64): 0…3 seconds |
| 16 | fmt.Printf("%T\n", r.N[uint8]) | we don’t call it, only instantiate it: %T prints the type of the value |
$ go run ./randn
7
92465
2.353284004s
func(uint8) uint8On the last line we gave the type by hand and got a function value of a concrete type: the method value from GO-1.12, only with instantiation first. The specification: “a generic method must be instantiated before it can be called or used as a value”.
Limit: a generic method implements no interface
Now to the condition from the start. It has two parts. Go 1.27 release notes: “methods of interfaces may not declare type parameters nor can interface methods be implemented by generic methods”.
Part one: an interface method cannot declare its own type parameter.
// imetod: ATAYLAB kompilyatsiya boʻlmaydi. Interface metodi type parameter e'lon qila olmaydi.
// go build -o /dev/null ./imetod (plain "go build ./imetod" collides with the folder name)
package main
type Aylantiruvchi interface {
Aylantir[U any](f func(int64) U) []U
}
func main() {}$ go build -o /dev/null ./imetod
# generics/imetod
imetod/main.go:6:10: interface method must have no type parameters
imetod/main.go:6:32: undefined: Uinterface method must have no type parameters. The second error follows from the first: [U any] was rejected,
so U is not declared (undefined). Using the interface’s own type parameters is allowed (the specification:
“they may use type parameters from the interface declaration”):
type Oluvchi[T any] interface{ Ol() T } // ruxsat: T interface'niki(The comment says: “allowed: T belongs to the interface”.)
Part two: a generic method implements no interface. ibajar/:
// ibajar: ATAYLAB kompilyatsiya boʻlmaydi. Generic metod interface metodini bajarmaydi.
// go build -o /dev/null ./ibajar (plain "go build ./ibajar" collides with the folder name)
package main
import "fmt"
type Bosh struct{}
func (Bosh) Nop[T any](x T) T { return x }
type MatnNop interface {
Nop(string) string
}
func main() {
var b Bosh
fmt.Println(b.Nop("salom"), b.Nop(42)) // toʻgʻridan-toʻgʻri: ishlaydi
var _ MatnNop = b // interface orqali: yoʻq
}| Line | Code | What it does |
|---|---|---|
| 7 | type Bosh struct{} | Bosh (“empty”): a struct with no fields |
| 9 | func (Bosh) Nop[T any](x T) T | a generic method: takes any T and returns it |
| 11–13 | type MatnNop interface { Nop(string) string } | an interface with a plain method that takes a string and returns a string |
| 17 | b.Nop("salom"), b.Nop(42) | a direct call: T = string, then int (comment: “directly: works”) |
| 18 | var _ MatnNop = b | an attempt to put Bosh into MatnNop; _ means we don’t need the value, only the check (comment: “through an interface: no”) |
In TypeScript the same code works: class Bosh { nop<T>(x: T): T } can be assigned to interface MatnNop \{ nop(x: string): string \} without trouble (checked with tsc 5.9.3). What about Go?
A) compiles, prints salom 42 · B) compile error on line 18 · C) compiles, panics on line 18
Answer
B. In Go 1.27 a generic method does not implement an interface method, even when it would match with
T = string. The compiler finds this in advance, so it is a compile error, not a panic. If you chose “A”, you
thought Go works like TypeScript. Line 17 is fine: the direct call works.
$ go build -o /dev/null ./ibajar
# generics/ibajar
ibajar/main.go:18:18: cannot use b (variable of struct type Bosh) as MatnNop value in variable declaration: Bosh does not implement MatnNop (wrong type for method Nop)
have Nop[T any](T) T
want Nop(string) stringWe read the error: cannot use b … as MatnNop value. The reason: Bosh does not implement MatnNop (wrong type for
method Nop). Then the difference: have Nop[T any](T) T, a generic method; want Nop(string) string, a plain
method.
Interestingly, the Go FAQ still calls this path “unacceptable”.
Why exactly this choice?
We saw in GO-1.13: an interface holds a (type, value) pair, and x.(T) checks the type while the
program runs. So implementing an interface is also checked while the program runs. A generic method, however, has
infinitely many variants: Nop[string], Nop[int], Nop[Ball], … The compiler writes into the binary only the
variants used in the code. If, while the program runs, someone asks the Bosh inside an any for
Nop(float32) float32, that variant may not be in the binary.
The Go FAQ (Why does Go not support methods with type parameters?) lists four ways:
| # | Way | Note |
|---|---|---|
| 1 | recompile the needed variants after linking | the build gets slower |
| 2 | JIT | compiling at runtime |
| 3 | slow fallback code | speed cannot be known in advance |
| 4 | a generic method implements no interface at all | FAQ: “unacceptable from a design point of view” → Go 1.27’s choice |
The fourth is called unacceptable there, but Go 1.27 chose exactly it. Griesemer wrote the reason in the proposal (golang/go#77273, “A change of view”): methods are needed not only for interfaces but also to organise code. His words: “concrete methods are a language feature that is useful in itself, irrespective of interfaces”. TypeScript does not have this problem: types are erased before the program runs, and one JS function serves every type.
We run the FAQ’s example in Go 1.27. We put a Bosh value into an empty interface and ask it for the Nop method:
// faq: Go FAQ'dagi misol (generic_methods), Go 1.27 da ishga tushirilgan.
// Bosh qiymati any ichida: dastur ishlayotganda uning generic metodi koʻrinmaydi.
// go run ./faq
package main
import (
"fmt"
"reflect"
)
type Bosh struct{}
func (Bosh) Nop[T any](x T) T { return x }
func (Bosh) Oddiy() {}
func main() {
var x any = Bosh{}
_, ok := x.(interface{ Nop(string) string })
fmt.Println("Nop(string) string bormi?", ok)
_, ok = x.(interface{ Nop(int) int })
fmt.Println("Nop(int) int bormi?", ok)
_, ok = x.(interface{ Oddiy() })
fmt.Println("Oddiy() bormi?", ok)
fmt.Println("reflect koʻrgan metodlar:", reflect.TypeOf(x).NumMethod())
}| Line | Code | What it does |
|---|---|---|
| 13 | func (Bosh) Nop[T any](x T) T | a generic method |
| 14 | func (Bosh) Oddiy() | Oddiy (“plain”): a plain method, for comparison |
| 17 | var x any = Bosh{} | Bosh inside an empty interface |
| 18, 20, 22 | _, ok := x.(interface{ … }) | a type assertion: “does the type inside x implement this interface?” If not, ok = false, no panic (GO-1.13). The printed text … bormi? means “is there …?“ |
| 24 | reflect.TypeOf(x).NumMethod() | reflect is the standard package that inspects types while the program runs; NumMethod counts the type’s methods (the text means “methods reflect saw”) |
Think: what do the four lines print?
A) true true true 2 · B) false false true 1 · C) true false true 2
Answer
B. Both Nop checks are false: a generic method implements no interface, at run time too. Oddiy is found.
reflect sees only one method. If you chose “C”, you thought Nop[string] exists even though the program never
called it. Even if it existed, the result would still be false: that is the rule.
$ go run ./faq
Nop(string) string bormi? false
Nop(int) int bormi? false
Oddiy() bormi? true
reflect koʻrgan metodlar: 1reflect also sees only one method, because it cannot fill a generic method with a concrete type. The proposal says:
“Generic methods also won’t be accessible via reflection”. So libraries that rely on reflect don’t see your
generic methods either.
Pause question: Katta(3, 2.5)
Now a question for you. We call the Katta function with 3 and 2.5:
// savol: Katta(3, 2.5) — kompilyatsiya boʻladimi? T nima boʻladi?
// go run ./savol
package main
import (
"cmp"
"fmt"
)
func Katta[T cmp.Ordered](a, b T) T {
if a > b {
return a
}
return b
}
func main() {
k := Katta(3, 2.5)
fmt.Printf("%v %T\n", k, k)
}Line 18 has Katta(3, 2.5); on line 19 %v is the value and %T its type. Does this code compile? If it does,
what does it print, and which type is T? Hint: both arguments are untyped constants.
A) compile error: int and float64 are mixed · B) 3 int · C) 3 float64
Answer
C. Both arguments are untyped constants. According to the specification, type inference picks the type of such
constants the same way as in a constant expression. When an integer and a floating-point constant mix, the
floating-point kind wins, and its default type is float64 (GO-1.03). Even though 3 is a
float64, %v prints it simply as 3. If you chose “A”, you thought 3 is an int right away: that is true for a
variable (x := 3), not for a constant. If you chose “B”, you thought the first argument decides the type.
$ go run ./savol
3 float64When you don’t need generics: three smells
Now the most important question: when don’t you need generics? hid/ (“smell”) has three generic functions. All of
them compile and run, but here the type parameter gives nothing.
// hid: uchta ortiqcha generic. Hammasi kompilyatsiya boʻladi va ishlaydi,
// lekin type parameter hech narsa bermaydi. Tozalangani: ../toza
// go run ./hid
package main
import (
"fmt"
"strconv"
)
type Buyurtma struct{ Summa int64 }
func (b Buyurtma) String() string { return fmt.Sprintf("buyurtma: %d soʻm", b.Summa) }
// 1-hid: T bilan faqat metod chaqiriladi.
func Chiqar[T fmt.Stringer](x T) { fmt.Println(x.String()) }
// 2-hid: T hech narsa bermaydi, Println baribir any oladi.
func Yoz[T any](x T) { fmt.Println("log:", x) }
// 3-hid: har bir tur uchun boshqa kod (type switch).
func Matn[T int64 | string](x T) string {
switch v := any(x).(type) {
case int64:
return strconv.FormatInt(v, 10)
case string:
return v
}
return ""
}
func main() {
Chiqar(Buyurtma{150000})
Yoz(42)
fmt.Println(Matn(int64(99000)), Matn("nok"))
}| Line | Code | What it does and why it is needless |
|---|---|---|
| 11–13 | Buyurtma, String() | Buyurtma (“order”): a type that implements fmt.Stringer (GO-1.13) |
| 16 | func Chiqar[T fmt.Stringer](x T) | Chiqar (“print”) only calls the String() method on T. Taylor: “If all you need to do with a value of some type is call a method on that value, use an interface type” |
| 19 | func Yoz[T any](x T) | Yoz (“write”): fmt.Println takes any value (any) anyway; T adds nothing |
| 22–30 | func Matn[T int64 | string](x T) string | Matn (“text”): inside is a type switch; any(x) converts T to the empty interface, then there is different code for each type. Taylor: “if the implementation is different for each type, then use an interface type … don’t use a type parameter” |
| 25 | strconv.FormatInt(v, 10) | turns an int64 into decimal text |
toza/ (“clean”) has the same three functions without type parameters:
// toza: ../hid dagi uchta funksiya type parameter'siz. Natija bir xil.
// go run ./toza
package main
import (
"fmt"
"strconv"
)
type Buyurtma struct{ Summa int64 }
func (b Buyurtma) String() string { return fmt.Sprintf("buyurtma: %d soʻm", b.Summa) }
// 1: faqat metod kerak — interface.
func Chiqar(x fmt.Stringer) { fmt.Println(x.String()) }
// 2: any yetarli.
func Yoz(x any) { fmt.Println("log:", x) }
// 3: har bir tur uchun oʻz kodi — alohida funksiyalar.
func MatnSon(x int64) string { return strconv.FormatInt(x, 10) }
func MatnSatr(x string) string { return x }
func main() {
Chiqar(Buyurtma{150000})
Yoz(42)
fmt.Println(MatnSon(99000), MatnSatr("nok"))
}Smell (hid/) | Clean (toza/) |
|---|---|
Chiqar[T fmt.Stringer](x T) | Chiqar(x fmt.Stringer): an interface |
Yoz[T any](x T) | Yoz(x any): any value |
Matn[T int64 | string] + type switch | MatnSon(int64) and MatnSatr(string): two separate functions (“text from number”, “text from string”) |
We compare the output of the two programs. diff <(…) <(…) compares the output of two commands line by line and
prints nothing if they are the same; && runs the next command only on success:
$ go run ./hid
buyurtma: 150000 soʻm
log: 42
99000 nok$ diff <(go run ./hid) <(go run ./toza) && echo natija bir xil
natija bir xil(natija bir xil means “the output is the same”.) The output is the same, and the code is simpler. Our practical
check is this: if nothing is lost when you remove the type parameter, it was needless. This is based on Taylor’s
advice, but it is not a strict rule: he says “consider”.
Are generics faster than interfaces? Let’s measure
Is generic code faster than an interface? Let’s measure. In tezlik/ (“speed”) the same sum is computed in three
ways:
// Package tezlik: bir xil yigʻindi uch usulda — interface, generic, oddiy tur.
// go test -bench . ./tezlik
package tezlik
type Buyurtma struct {
Summa int64
Tolandi bool
}
func (b *Buyurtma) Jami() int64 { return b.Summa }
type Summali interface{ Jami() int64 }
//go:noinline
func JamiInterface(xs []Summali) (s int64) {
for _, x := range xs {
s += x.Jami()
}
return s
}
//go:noinline
func JamiGeneric[T Summali](xs []T) (s int64) {
for _, x := range xs {
s += x.Jami()
}
return s
}
//go:noinline
func JamiOddiy(xs []*Buyurtma) (s int64) {
for _, x := range xs {
s += x.Jami()
}
return s
}| Line | Code | What it does |
|---|---|---|
| 10 | func (b *Buyurtma) Jami() int64 | a method with a pointer receiver: returns the amount |
| 12 | type Summali interface{ Jami() int64 } | Summali (“has an amount”): types with a Jami method |
| 14, 22, 30 | //go:noinline | tells the compiler: don’t copy this function itself into the call site. So that the benchmark measures the function |
| 15 | JamiInterface(xs []Summali) | a slice of interfaces |
| 23 | JamiGeneric[T Summali](xs []T) | generic: T = *Buyurtma |
| 31 | JamiOddiy(xs []*Buyurtma) | Oddiy (“plain”): a plain concrete type |
| 15, 23, 31 | (s int64) | a named result: s starts at 0, return s returns it |
The benchmarks (GO-1.07) use 1000 orders:
package tezlik
import "testing"
const n = 1000
func buyurtmalar() []*Buyurtma {
xs := make([]*Buyurtma, n)
for i := range xs {
xs[i] = &Buyurtma{Summa: int64(i)}
}
return xs
}
func TestBirXil(t *testing.T) {
xs := buyurtmalar()
is := make([]Summali, n)
for i, x := range xs {
is[i] = x
}
a, b, c := JamiInterface(is), JamiGeneric(xs), JamiOddiy(xs)
if a != b || b != c {
t.Fatalf("%d %d %d", a, b, c)
}
}
func BenchmarkInterface(b *testing.B) {
xs := buyurtmalar()
is := make([]Summali, n)
for i, x := range xs {
is[i] = x
}
for b.Loop() {
JamiInterface(is)
}
}
func BenchmarkGeneric(b *testing.B) {
xs := buyurtmalar()
for b.Loop() {
JamiGeneric(xs)
}
}
func BenchmarkOddiy(b *testing.B) {
xs := buyurtmalar()
for b.Loop() {
JamiOddiy(xs)
}
}TestBirXil (“same”) checks that all three functions give the same sum. The three benchmarks measure the same 1000
orders; for the interface version they are first copied into a []Summali (lines 17–20).
One measurement is noisy, so olch.sh (“measure”) runs each benchmark 7 times and takes the median:
#!/usr/bin/env bash
# olch.sh: har bir benchmark'ni 7 marta ishga tushirib, medianasini chiqaradi (shovqinni kamaytirish uchun).
# ./tezlik/olch.sh (lessons/017-generics papkasidan)
set -euo pipefail
cd "$(dirname "$0")"
go test -run '^$' -bench . -count 7 -cpu 1 . |
awk '/^Benchmark/ { v[$1] = v[$1] " " $3 }
END {
for (k in v) {
n = split(substr(v[k], 2), a, " ")
for (i = 1; i <= n; i++) for (j = i + 1; j <= n; j++) if (a[j] < a[i]) { t = a[i]; a[i] = a[j]; a[j] = t }
printf "%-20s %8.0f ns/op (mediana, %d marta)\n", k, a[int((n + 1) / 2)], n
}
}' | sort -k2 -n -r-run '^$' skips the tests, -count 7 means 7 times, -cpu 1 means one core. awk sorts the 7 results of each
benchmark and prints the middle one (mediana, 7 marta = “median, 7 times”).
Think: what will the result look like?
A) generic fastest, interface slowest · B) interface and generic almost the same, the plain type several times faster · C) all three almost the same
Answer
B. The reason is below. If you chose “A”, you thought generics produce separate code for each type: the standard Go compiler does not do that. If you chose “C”, you did not take inlining into account.
$ ./tezlik/olch.sh
BenchmarkInterface 2038 ns/op (mediana, 7 marta)
BenchmarkGeneric 1961 ns/op (mediana, 7 marta)
BenchmarkOddiy 450 ns/op (mediana, 7 marta)These numbers depend on the machine’s load. This result was taken on a busy machine (load average ≈ 11); the video
shows a result under lighter load: 1593, 1558 and 287 ns/op. You will get other numbers. But the picture is the
same: interface and generic are very close to each other (sometimes one is ahead, sometimes the other), and the
plain type is several times faster than both (≈ 4.4× here, 5–6× under light load). All three variants are
0 allocs/op: no memory allocation.
The reason is in the compiler. First: in the plain version the Jami method is inlined, which means the call
disappears. -gcflags=-m (GO-1.11) prints the compiler’s decisions:
$ go build -gcflags=-m ./tezlik 2>&1 | grep 'inlining call'
tezlik/tezlik.go:33:14: inlining call to (*Buyurtma).Jami2>&1 sends the compiler’s messages (stderr) to grep. Line 33 is x.Jami() inside JamiOddiy. On lines 17 and
25 (interface and generic) there is no inlining: there is a real call every time.
Second: the standard Go compiler does not build a generic function separately for each type. It builds one shared
body for all pointer types. Such a group of bodies is called a shape; all pointer types share the one
go.shape.*uint8 shape. The body learns which concrete type it is working with through a hidden argument, the
dictionary. The method is called through this dictionary too, just like through an interface. go tool nm shows
the names in the binary:
$ go test -c -o /tmp/tezlik.test ./tezlik && go tool nm /tmp/tezlik.test | grep JamiGeneric
5656e0 R generics/tezlik..dict.JamiGeneric[*generics/tezlik.Buyurtma]
544560 T generics/tezlik.JamiGeneric[go.shape.*uint8]go test -c does not run the test, it only builds the binary. T is code (a function body):
JamiGeneric[go.shape.*uint8], one for all pointer types. R is read-only data: the dictionary for *Buyurtma.
In the guru homework task you count yourself how many bodies come out with four types.
| Interface | Generic (T = *Buyurtma) | Plain | |
|---|---|---|---|
how Jami is called | through the interface table | through the dictionary | directly, inlined |
| is there a call | yes, for each element | yes, for each element | no |
| speed | slow | slow | several times faster |
These are details of the standard (gc) compiler. The Go FAQ: “Different compilers will make different choices”. Taylor wrote this too: “don’t change from interface types to type parameters just for speed, because it probably won’t run any faster”.
Summary: do you need generics?
| Situation | What to use |
|---|---|
| only for speed | no, measure first |
the same code, different types (slice, map, container: Katta, Royxat[T]) | a type parameter [T] |
| you only need a method of the value, or the code differs for each type | an interface (or separate functions) |
a method returns a new type (Aylantir[U]) | a generic method (Go 1.27+): convenient, but not callable through an interface |
Common mistakes
1. Expecting a generic method to implement an interface. Someone coming from TypeScript puts nop<T> into an
interface with nop(string) without a second thought. In Go 1.27, var _ MatnNop = b → Bosh does not implement MatnNop (wrong type for method Nop), have Nop[T any](T) T, want Nop(string) string (the “Limit” section).
At run time too: x.(interface{ Nop(string) string }) → false (the “Why exactly this choice?” section). Fix: if
you need the interface, write a plain method (func (Bosh) NopMatn(x string) string), or make the type itself
generic (type Bosh[T any] struct{} and func (Bosh[T]) Nop(x T) T): then Bosh[string] implements MatnNop.
2. Forgetting ~. Son interface{ int64 | float64 } and type Ball int64 → Ball does not satisfy Son (possibly missing ~ for int64 in Son) (the “A constraint is an interface” section). Fix: ~int64 | ~float64.
In a constraint that must work with your own types, always put ~, like cmp.Ordered does.
3. Taking a generic method as a value without instantiation. The method value from GO-1.12
(f := b.Jami) does not work with a generic method. This program is not in the course folder; it was run in a
separate module (go 1.27):
package main
import "fmt"
type Quti[T any] struct{ v T }
func (q Quti[T]) Juft[U any](u U) (T, U) { return q.v, u }
func main() {
q := Quti[int]{7}
f := q.Juft
fmt.Println(f("yetti"))
}$ go run ./juft
# scratch/juft
juft/main.go:11:7: cannot use generic function q.Juft without instantiationcannot use generic function q.Juft without instantiation. The compiler does not know which type f should have:
U is still unknown. (Quti = “box”, Juft = “pair”, yetti = “seven”.) Fix: give the type,
f := q.Juft[string], or write the type of f: var f func(string) (int, string) = q.Juft.
4. Writing a type parameter on an interface method. Aylantir[U any](…) inside an interface → interface method must have no type parameters (the “Limit” section, part one). Fix: put the type parameter on the interface itself
(type Aylantiruvchi[U any] interface{ Aylantir(f func(int64) U) []U }) or write a package-level generic function.
5. New Go, old go line. Go 1.27.4 is installed, but go.mod has go 1.26 → generic method requires go1.27 or later (-lang was set to go1.26; check go.mod) (the “go.mod condition” section). Fix: make the go line
go 1.27 (go get go@1.27), but in a library this forces its users onto Go 1.27 too.
6. go build ./folder and a binary named like the folder. The comment in the course files says
go build ./tildesiz. If you run exactly that, you get another message instead of the compile error:
$ go build ./tildesiz
go: build output "tildesiz" already exists and is a directorybuild output “tildesiz” already exists and is a directory. go build builds a binary from a single main package
and wants to write it into the current folder under the package’s name. Here a folder with that name already exists,
so go does not even get to compiling. Fix: go build -o /dev/null ./tildesiz (no binary needed) or
go vet ./tildesiz.
7. Needless generics and the belief that “generics are faster”. No error, the code works, but it is needlessly complex (the “When you don’t need generics” section). Speed barely changes either (the “Are generics faster than interfaces?” section). Fix: try removing the type parameter; if nothing is lost, it was needless.
Check yourself
1. In func Katta[T cmp.Ordered](a, b T) T, which is the type parameter and which is the constraint? What is
int64 called in Katta[int64](1, 2)?
Answer
T is the type parameter, cmp.Ordered is the constraint. int64 is a type argument: the compiler puts it in place
of T, which is instantiation. In Katta(1, 2) type inference finds the type (int).
2. What does this program print? (Katta is the function from the lesson; not in the course folder, run
separately.)
fmt.Println(Katta("10", "9"), Katta(10, 9))Answer
$ go run ./satr
9 10Strings compare byte by byte, not as numbers: the first byte of "9", '9', is bigger than the first byte of
"10", '1'. In Katta(10, 9), T = int and the result is 10.
3. Which one should be generic, and which should not?
(a) func Oxirgi[T any](s []T) T { return s[len(s)-1] }
(b) func Yop[T io.Closer](c T) error { return c.Close() }
Answer
(a) Oxirgi (“last”) should be generic: the same code for any element type, and the result is exactly T (with an
interface the result would become any). (b) Yop (“close”) is needless: T is used only to call a method, so
func Yop(c io.Closer) error is enough (the first smell).
4. In Go 1.27, type Bosh struct{} has the method func (Bosh) Nop[T any](x T) T. Why does Bosh not
implement interface{ Nop(string) string }, and why did the Go team leave it that way?
Answer
The Go 1.27 rule: a generic method does not implement an interface method. Implementing an interface is also checked while the program runs, and a generic method has infinitely many variants, while the binary contains only the ones that are used. The other three of the FAQ’s four ways (recompiling after linking, JIT, slow fallback code) make the build or the speed worse. Go 1.27 chose the fourth, because methods are useful even without interfaces (Griesemer, #77273).
5. From GO-1.13: after var x any = Bosh{}, what happens if v, ok := x.(MatnNop) does not
match? And with v := x.(MatnNop), without ok?
Answer
With ok: ok = false, v is the zero value of MatnNop (nil), no panic. Without ok: if it does not match,
the program stops with a panic. That is why today’s faq/ program uses the ok form.
Homework
Four tasks at four levels. All files are in the lesson folder on GitHub: lessons/017-generics . Answers: the homework/ folder. Try it yourself first.
🟢 Easy: write Indeks[T comparable](s []T, x T) int: the position where x first appears, or -1 if it is
not found. Compare it with slices.Index.
Answer
// oson: Indeks — x birinchi uchragan oʻrin yoki -1. Bitta generic funksiya.
// go run ./homework/oson
package main
import (
"fmt"
"slices"
)
func Indeks[T comparable](s []T, x T) int {
for i, v := range s {
if v == x {
return i
}
}
return -1
}
func main() {
fmt.Println(Indeks([]int64{150000, 99000}, 99000))
fmt.Println(Indeks([]string{"olma", "nok"}, "uzum"))
// Standart kutubxonada tayyori bor (Go 1.21+):
fmt.Println(slices.Index([]int64{150000, 99000}, 99000))
}$ go run ./homework/oson
1
-1
1comparable is a constraint built into the language for types that compare with == and !=. Line 12 has
v == x, so any is not enough. slices.Index (Go 1.21+) does exactly this: in real code use the ready one.
🟡 Medium: type Quti[T any] struct{ v T }. Which lines compile in Go 1.27?
func (q Quti[T]) Ol() T { return q.v }func (q Quti[T]) Juft[U any](u U) (T, U) { return q.v, u }type I interface{ M[T any](T) }f := q.Juftvar o Oluvchi[int] = q(wheretype Oluvchi[T any] interface{ Ol() T })f := q.Juft[string]
Answer
1, 2, 5 and 6 compile. 3 gives interface method must have no type parameters (the “Limit” section). 4 gives
cannot use generic function q.Juft without instantiation (“Common mistakes”, 3). 5: a generic interface is a
different thing: its method Ol() (“get”) is plain and only uses the interface’s T, so Quti[int] implements
it. The ones that compile:
// orta: README dagi 6 qatordan kompilyatsiya boʻladiganlari (1, 2, 5, 6).
// 3 va 4 — ATAYLAB yoʻq: ular kompilyatsiya boʻlmaydi.
// go run ./homework/orta
package main
import "fmt"
type Quti[T any] struct{ v T }
// 1: generic turdagi metod, receiver'dagi T bilan (Go 1.18+)
func (q Quti[T]) Ol() T { return q.v }
// 2: generic turdagi metod, oʻz type parametri bilan (Go 1.27+)
func (q Quti[T]) Juft[U any](u U) (T, U) { return q.v, u }
type Oluvchi[T any] interface{ Ol() T }
func main() {
q := Quti[int]{7}
// 5: generic interface'ni oddiy metod bajaradi
var o Oluvchi[int] = q
fmt.Println(o.Ol())
// 6: generic metoddan aniq tur bilan method value
f := q.Juft[string]
fmt.Println(f("yetti"))
}$ go run ./homework/orta
7
7 yetti🟠 Hard: add a generic method Guruhla[K comparable](kalit func(T) K) map[K]Royxat[T] to Royxat[T] and test
it: once with a bool key and once with a string key.
Answer
// Package qiyin: Guruhla — Go 1.27 generic metodi. K — metodning oʻz type parametri.
package qiyin
type Royxat[T any] []T
// Guruhla elementlarni kalit(x) boʻyicha guruhlaydi; har guruhda tartib saqlanadi.
func (r Royxat[T]) Guruhla[K comparable](kalit func(T) K) map[K]Royxat[T] {
natija := make(map[K]Royxat[T])
for _, x := range r {
k := kalit(x)
natija[k] = append(natija[k], x)
}
return natija
}Guruhla (“group by”), kalit (“key”). K is the method’s own type parameter, comparable because it is a map
key. natija[k] returns a nil slice for a missing key, and append works on it too (GO-1.08,
GO-1.09). The test (homework/qiyin/qiyin_test.go) groups once by Tolandi (“paid”, a bool)
and once by "katta"/"kichik" (“big”/“small”, a string):
$ go test -count=1 ./homework/qiyin
ok generics/homework/qiyin 0.002s-count=1 runs the test again instead of taking it from the cache. Your time will differ.
🔴 Guru: call JamiGeneric[T Summali] with *Buyurtma, *Mijoz, Narx (based on int64) and Chegirma
(based on int64). How many bodies and how many dictionaries does the compiler build? Check with go tool nm.
Answer
2 bodies, 4 dictionaries (the standard gc compiler, go1.27.4):
$ go test -c -o /tmp/guru.test ./homework/guru && go tool nm /tmp/guru.test | grep JamiGeneric
565480 R generics/homework/guru..dict.JamiGeneric[*generics/homework/guru.Buyurtma]
5654a0 R generics/homework/guru..dict.JamiGeneric[*generics/homework/guru.Mijoz]
5654e0 R generics/homework/guru..dict.JamiGeneric[generics/homework/guru.Chegirma]
5654c0 R generics/homework/guru..dict.JamiGeneric[generics/homework/guru.Narx]
543d00 T generics/homework/guru.JamiGeneric[go.shape.*uint8]
543c40 T generics/homework/guru.JamiGeneric[go.shape.int64]Both pointer types share one go.shape.*uint8 body, and Narx (“price”) and Chegirma (“discount”) share one
go.shape.int64 body. The difference between the types (which Jami) is in the dictionary. The addresses (first
column) will be different for you.
Sources
- Go 1.27 Release Notes: Changes to the language (generic methods, the
interface limit) and math/rand/v2 (
Rand.N) - The Go specification (Language version go1.27): Method declarations , Basic interfaces , General interfaces , Type parameter declarations , Instantiations , Type inference
- golang/go#77273 «spec: generic methods for Go» (R. Griesemer, 2026)
- Go FAQ: Why does Go not support methods with type parameters? , generics_implementation
- I. L. Taylor, When To Use Generics (Go blog, 2022)
- R. Griesemer, I. L. Taylor, An Introduction To Generics (Go blog, 2022)
- Generics implementation: dictionaries (go1.18)
- Go 1.21 Release Notes (
min,max) - Go source code (go1.27.4): src/cmp/cmp.go , src/math/rand/v2/rand.go
- Go Toolchains (the
goline,GOTOOLCHAIN) - Other languages: TypeScript Handbook: Generics , PEP 695: Type Parameter Syntax , PHPStan: Generics in PHP using PHPDocs
- All Go results were taken with
go1.27.4 linux/amd64(the old example withgo1.26.8), Intel i5-12450H, on 2026-11-26. For comparison: TypeScript 5.9.3 (Node.js v24.10.0), Python 3.13.15.
Video and code
▶️ The video is coming soon. This page teaches the whole lesson, so you don’t have to wait for it.
💻 Code and homework answers on GitHub
← Previous lesson: GO-1.16 · Next lesson: GO-1.18 → · All lessons
comments