How to Write a Generic Function in Go

Define a generic function in Go by adding type parameters in square brackets after the function name to handle multiple types.

Write a generic function by declaring type parameters in square brackets after the function name and using them as types for parameters or return values.

func Max[T comparable](a, b T) T {
	if a < b {
		return b
	}
	return a
}

func main() {
	fmt.Println(Max(1, 2))
	fmt.Println(Max("a", "b"))
}