Inspect generic instantiation strategies
Inspect generic instantiation strategies
Instantiating a generic function substitutes type arguments that satisfy its constraints. Go 1.23 compiler noder/reader.go and stencil.go implement shape-based code sharing and dictionaries (metadata used for type-dependent operations); wrappers may call shared bodies. This avoids requiring a completely separate machine-code body for every named type. Exact shape groups, dictionary layout, symbols and inlining are implementation details, not a language requirement. Compare concrete types at the public type-checker level before looking at symbols.
package main
import ( "fmt")
type Count int
//go:noinlinefunc twice[T ~int | ~int64](x T) T { return x + x }func main() { fmt.Println(twice(3), twice(Count(4)), twice(int64(5)))}Count satisfies ~int because its underlying type is int. The result retains Count when Count is supplied. Save this example as main.go and run go build -gcflags=-l -o demo main.go, then go tool nm demo. In Go 1.23 look for main.twice[go.shape.int] and main.twice[go.shape.int64] plus dictionary symbols. The directive makes this inspection easier; do not depend on these names in production.
Expected output:
6 8 10Inspect type arguments, not private dictionaries
package main
import ( "fmt" "go/ast" "go/parser" "go/token" "go/types")
func main() { fs := token.NewFileSet() f, e := parser.ParseFile(fs, "p.go", `package p; func id[T any](x T)T{return x}; var v=id(7)`, 0) if e != nil { panic(e) } info := types.Info{Instances: map[*ast.Ident]types.Instance{}} c := types.Config{} _, e = c.Check("p", fs, []*ast.File{f}, &info) if e != nil { panic(e) } for id, inst := range info.Instances { fmt.Println(id.Name, inst.TypeArgs.At(0), inst.Type) }}Info.Instances records inferred or explicit type arguments and instantiated types. There is only one entry here; for multiple entries sort by source position. This describes semantic instantiation, not how many machine-code copies exist. The compiler may inline a call so the corresponding symbol disappears.
Expected output:
id int func(x int) intTry it locally
Write a generic increment function for ~int and ~int64. Define type Score int; print the value and dynamic type of increment(Score(9)), and increment(int64(2)).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Compiler pipeline 03: Inspect generic instantiation strategies
Check the lesson objective before moving on.
What must a type argument satisfy?
Does one instantiation necessarily imply a separate machine-code body?