Home > Article > Backend Development > Go language generics implement multi-type support
Go language generics provide multi-type support, allowing developers to create code that can be used for multiple types. Generic syntax declares a generic type by specifying type parameters in the type name, and automatically infers the type parameters in function calls. Generics support comparable types and can be used to create common algorithms and functions, such as the universal sorting algorithm, which uses custom comparison functions to sort various types.
The Go language introduced generics features in version 1.18, allowing developers to create multi-type code. Generics can improve code reusability and flexibility.
When declaring a generic type, you need to specify the type parameters in square brackets in the type name:
func Max[T comparable](a, b T) T { if a > b { return a } return b }
When using a generic type in a function call, The Golang compiler will automatically infer type parameters:
fmt.Println(Max(1, 2)) // 输出:2 fmt.Println(Max(1.2, 3.4)) // 输出:3.4 fmt.Println(Max("Hello", "Wolrd")) // 输出:Wolrd
It should be noted that generic types only support comparable types (comparable
).
Using generics, we can create a universal sorting algorithm applicable to any type:
func Sort[T any](arr []T, less func(T, T) bool) { for i := 0; i < len(arr); i++ { for j := 0; j < len(arr)-1-i; j++ { if less(arr[j], arr[j+1]) { arr[j], arr[j+1] = arr[j+1], arr[j] } } } }
Using a custom comparison function, we can This sorting algorithm is used for various types:
func SortInts(arr []int) { Sort(arr, func(a, b int) bool { return a < b }) } func SortStrings(arr []string) { Sort(arr, func(a, b string) bool { return a < b }) }
The generics feature in the Go language provides powerful multi-type support, allowing developers to create reusable and flexible code. By using the techniques presented above, we can easily create general-purpose algorithms and functions that work across many types.
The above is the detailed content of Go language generics implement multi-type support. For more information, please follow other related articles on the PHP Chinese website!