liveBook · Manning

Type inference

As explained in 100 Go Mistakes and How to Avoid Them

Type inference is the compile-time deduction of generic type arguments from a call or use context.

A common mistake is to treat generic calls as requiring explicit type arguments. Go can infer the arguments from the call context: getKeys(m) infers K and V from m, while getKeys[string](m) supplies K explicitly. section 2.9.1

Infer from a map argument

With m declared as map[string]int, keys := getKeys(m) selects K as string and V as int at compile time. The explicit form, keys := getKeys[string](m), is useful when inference needs clarification. section 2.9.1

Choose the call form according to the situation:

  • Use getKeys(m) when the argument provides enough information and the inferred types are clear. section 2.9.1
  • Use getKeys[string](m) when making a type argument explicit improves readability or resolves ambiguity. section 2.9.1
  • Keep constraints such as comparable on inferred parameters when the generic operation requires them; map keys cannot use arbitrary any types. section 2.9.1
m = map[string]int{
    "one":   1,
    "two":   2,
    "three": 3,
}
keys := getKeys(m)

Compare inferred and explicit generic calls through the accompanying getKeys examples. section 2.9.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Demonstrates inferred and explicit calls, but does not detail the compiler's inference algorithm.
Examples
Uses getKeys on map[string]int and contrasts inferred getKeys(m) with explicit getKeys[string](m).
What it assumes
Assumes familiarity with functions and maps, then introduces type parameters, instantiation, and constraints.
What you can do after
Apply it via generic functions by choosing inferred calls when arguments suffice and explicit type arguments when clarity requires them.
How it connects
Connects type parameters with generics, type constraints, map types, and compile-time type checking.

Also explained in

Compare how 16 books explain type inference →

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.