Infer type arguments
Infer type arguments
For generic function calls, the compiler can often infer type arguments from value arguments and constraints. Explicit arguments remain useful when inference is ambiguous or has insufficient information. Inference is compile-time reasoning, not inspection of runtime values.
package main
import ( "fmt")
func twice[T ~int | ~string](x T) T { return x + x }func main() { fmt.Println(twice(3), twice("go"))}The untyped integer and string constants infer int and string respectively. The union constraint permits both types and their defined variants, so addition is valid for every permitted type.
Expected output:
6 gogoInfer an element type from a slice
package main
import ( "fmt")
func first[S ~[]E, E any](s S) E { return s[0] }
type Names []string
func main() { fmt.Println(first(Names{"Ada", "Lin"})) fmt.Println(first[[]int]([]int{5, 6}))}S is inferred from the argument and E from its underlying slice element type. A partial explicit type argument list is a prefix; the rest may be inferred. This function requires nonempty input. A function with no arguments such as zeroT any T generally needs explicit T in a direct call.
Expected output:
Ada5Try it locally
Write last[T any](s []T) T for nonempty slices and infer T when calling with []string{"a","b"}.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generics 02: Infer type arguments
Check the lesson objective before moving on.
When does type inference occur?
What can you do when a direct call cannot infer T?