skip to content
Alvin Lucillo

Type inference

/ 1 min read

💻 Tech

In Go, a function that uses generics can infer the type T from its arguments. In the example below, when calling Mult, we don’t need to specify the type like this: Mult[A](...). Instead, the type T will be inferred from obj argument.

package main

import "fmt"

type A struct{ name string }
type B struct{ name string }

func main() {
	x := Mult(A{name: "hello"})
	fmt.Printf("%#v: \n", x)
	y := Mult(B{name: "hello"})
	fmt.Printf("%#v: \n", y)
}

func Mult[T any](obj T) []T {
	return []T{obj, obj}
}
[]main.A{main.A{name:"hello"}, main.A{name:"hello"}}:
[]main.B{main.B{name:"hello"}, main.B{name:"hello"}}: