Home >Backend Development >Golang >How do Golang generics handle different types of data in functions?
Go generics allow functions to handle different types of data through type parameters. By using the comparable type parameter T, the Max function can return the larger of two values, working for any comparable type.
Go Generics allow us to create common code that works across multiple types. Here's how to use generics in a Go function to handle different types of data:
func Max[T comparable](a, b T) T { if a > b { return a } return b }
Max
The function takes a type parameter T
as input, making it applicable to any Type of comparison. It returns type T
, which is the same as the input type.
Practical case:
The following example shows how to use the Max
function:
// 找到两个整数的最大值 maxInt := Max(10, 20) // 找到两个浮点数的最大值 maxFloat := Max(3.14, 2.71) // 找到两个字符串的最大值(使用字符串比较) maxString := Max("Hello", "World") fmt.Println(maxInt, maxFloat, maxString) // 输出:20 3.14 Hello
Go generics make creation applicable It becomes easy to work with many types of code. It allows us to write generic and reusable functions, thereby improving code readability and maintainability.
The above is the detailed content of How do Golang generics handle different types of data in functions?. For more information, please follow other related articles on the PHP Chinese website!