liveBook · Manning

Template instantiation

As explained in 100 Go Mistakes and How to Avoid Them

Instantiation is the compile-time process of applying concrete type arguments to a generic function or type.

Instantiation is the compile-time act of supplying concrete type arguments to a generic function or type. It preserves type safety in the language and avoids runtime overhead. section 2.9.1

func foo[T any](t T) {     #1
    // ...
}

The generic function declares a type parameter; calling it with a concrete type argument instantiates that function. section 2.9.1

Explicit instantiation with getKeys

A generic map helper can accept a concrete type argument explicitly: keys := getKeys[string](m). The selected key type must satisfy the function's constraint; an unconstrained slice type cannot be used as a map key. section 2.9.1 section 2.9.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines compile-time application and contrasts it with runtime type checking, but does not descend into compiler implementation.
Examples
Uses generic foo, the getKeys map helper, explicit getKeys[string](m), and invalid slice map keys.
What it assumes
Assumes familiarity with functions, types, maps, and interfaces while introducing type parameters, type arguments, and constraints.
What you can do after
Apply it via Go generics by supplying concrete type arguments to generic functions and respecting their constraints.
How it connects
Connects instantiation with generics, type parameters, type arguments, constraints, and compile-time type safety.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.