Home >Backend Development >Golang >Generics of golang functions
Function generics in Go language
Generic functions allow you to define common functions for various types, thereby improving the reusability of your code sex and flexibility.
Syntax
The syntax of a generic function is as follows:
func <函数名>[T any](<参数列表>) <返回值类型> { // 函数体 }
Where:
<function name></function>
is the name of the generic function. <t any></t>
indicates the type parameters accepted by the function, and the any
keyword indicates that the type is unknown. <parameter list></parameter>
are the parameters required by the function. <return value type></return>
is the type returned by the function. Practical case
We create a generic function that compares two values and returns the larger value:
func Max[T comparable](a, b T) T { if a > b { return a } return b }
We can use This function compares two values of any comparable type:
maxInt := Max(10, 20) // int maxString := Max("hello", "world") // string
Constraints
You can use type constraints to limit the types that a function can accept. For example, you can require that types must be comparable or implement a specific interface: Use may reduce performance.
Generic type instantiation will generate new types, which may increase memory overhead.
The above is the detailed content of Generics of golang functions. For more information, please follow other related articles on the PHP Chinese website!