Go Type Inference
Type inference lets the compiler work out a generic type argument from the values at a call. The call can stay short when the values already carry the type.
Inference from the arguments
Pair takes two values of one type. The calls pass plain values, and the compiler reads the type from them.
package main
import "fmt"
func Pair[T any](first, second T) [2]T {
return [2]T{first, second}
}
func main() {
fmt.Println(Pair(3, 7))
fmt.Println(Pair("go", "lang"))
}Naming the type when inference cannot
Parse builds its result type from digits alone, so no argument carries that type. The call names int in brackets.
package main
import "fmt"
func Parse[T ~int](text string) T {
var value T
for _, ch := range text {
value = value*10 + T(ch-'0')
}
return value
}
func main() {
n := Parse[int]("42")
fmt.Println(n)
fmt.Println(n + 8)
}Mixed types refuse to compile
Pair needs one type for both values. An int and a string give inference no single type, so the compiler refuses the call.
package main
import "fmt"
func Pair[T any](first, second T) [2]T {
return [2]T{first, second}
}
func main() {
fmt.Println(Pair(1, "one"))
}Example
package main
import "fmt"
func Pair[T any](first, second T) [2]T {
return [2]T{first, second}
}
func Parse[T ~int](text string) T {
var value T
for _, ch := range text {
value = value*10 + T(ch-'0')
}
return value
}
func main() {
fmt.Println(Pair(3, 7))
fmt.Println(Pair[string]("go", "lang"))
fmt.Println(Parse[int]("42"))
}Key points
- Inference reads the argument values at a call and fills in the type parameter.
- A call can still name the type argument in brackets, as in Parse[int].
- Inference has nothing to read when no argument carries the type the function builds.
- A helper that builds a value of type T from digits must be told which T to build.
- Mixed argument types give inference no single answer, and the call fails to compile.
In this example, the first Pair call lets inference read int from 3 and 7. The second Pair call names string in brackets and prints the same pair shape. The Parse call names int because its digits alone carry no result type.
Note
Inference changes only how a call is written, never what the code does.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Go Playground
Exercise
When must a call name its type argument?