liveBook · Manning

Type inference

As explained in Learn Go with Pocket-Sized Projects

Type inference is the compiler's deduction of a generic type argument from the types of a function's input arguments.

Type inference lets the Go compiler deduce a generic function's type argument from its input arguments, so callers can often omit explicit type arguments. section 7.1.1

A generic function declares a type parameter such as T and a constraint such as any. When T appears in an input parameter, the compiler determines its concrete type at each call. Inference does not use returned types. section 7.1.1

Omitting explicit type arguments

func prettyPrint[T any](t T) { fmt.Printf("> %v", t) } prettyPrint(.25) // T is inferred as float64 prettyPrint("pockets") // T is inferred as string section 7.1.1

func prettyPrint[T any](t T){
    fmt.Printf("> %v", t)
}

prettyPrint(.25) #1
prettyPrint("pockets") #2

Compare the generic function declaration with calls that rely on compiler inference. section 7.1.1

Type inference has these boundaries:

  • Infer type arguments from input parameters when the generic type appears there. section 7.1.1
  • Write explicit square-bracket type arguments when inference cannot determine the desired type. section 7.1.1
  • Do not expect inference to derive a type solely from a function's returned type. section 7.1.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains input-based deduction and its returned-type limitation, while stopping short of compiler algorithm internals.
Examples
Uses a generic prettyPrint function called with float64 and string arguments.
What it assumes
Assumes familiarity with functions and types, while introducing generic type parameters, constraints, and inference.
What you can do after
Apply it via Go generic functions by omitting type arguments when input parameters determine them.
How it connects
Connects type inference to generics, generic functions, type parameters, and type constraints.

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 Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.