liveBook · Manning

Type argument

As explained in 100 Go Mistakes and How to Avoid Them

A type argument is a concrete type supplied for a generic type parameter.

A type argument is the concrete type supplied for a generic type parameter. Supplying one instantiates the generic function or type at compile time, preserving type safety and avoiding runtime overhead. section 2.9.1

Explicit and contextual type arguments

Given `func getKeys[K comparable, V any](m map[K]V) []K`, a string-keyed map can be passed as `keys := getKeys(m)`. The type argument can also be written explicitly: `keys := getKeys[string](m)`. Both calls use `string` for `K`; the explicit form makes that choice visible. section 2.9.1

Check the constraint before choosing a type argument:

  • `K comparable` accepts key types usable with `==` or `!=`; `[]byte` is rejected as an invalid map key type. section 2.9.1
  • A custom constraint can narrow the permitted arguments, such as `~int | ~string`, rather than accepting every comparable type. section 2.9.1
keys := getKeys[string](m)

The explicit type argument appears between brackets before the function call’s ordinary arguments. section 2.9.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains instantiation, explicit calls, and constraint failures, but stops short of detailed type-inference rules.
Examples
Demonstrates generic map-key extraction, explicit string arguments, invalid slice keys, and custom type constraints.
What it assumes
Assumes familiarity with Go functions, maps, interfaces, and compile-time versus runtime checking.
What you can do after
Apply generics by supplying valid concrete types to generic functions and recognizing constraint violations.
How it connects
Connects type arguments with type parameters, generics, constraints, interfaces, and comparable map keys.

Also explained in

Compare how 5 books explain type argument →

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.