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"))
}
A generic function is a single function definition that works with any data type, like a reusable mold for different shapes. Instead of writing separate functions for integers, strings, and floats, you write one function that adapts to whatever type you pass it. This keeps your code shorter and reduces the chance of copy-paste errors.