Home >Backend Development >Golang >Does Go Use Empty Interfaces or Type Parameters for Generic Functions?
Generic Functions in Go
In Go, the concept of generic functions finds its implementation through the usage of an empty interface. An empty interface, due to not requiring any additional method implementations, has the capability of holding any type of value. This leads to the question of whether this serves as Go's approach to generic function implementation or if there exists a more suitable alternative.
As of Go 1.18, a more modern and explicit method for defining generic functions has been introduced. It leverages type parameters to specify the types that the function can operate on. For example, consider the following generic function Print:
package main import ( "fmt" ) // T can be any type func Print[T any](s []T) { for _, v := range s { fmt.Print(v) } } func main() { // Passing list of string works Print([]string{"Hello, ", "world\n"}) // You can pass a list of int to the same function as well Print([]int{1, 2}) }
Output:
Hello, world 12
This method provides a cleaner and more explicit declaration of generic functions, making it easier to understand and maintain the codebase.
The above is the detailed content of Does Go Use Empty Interfaces or Type Parameters for Generic Functions?. For more information, please follow other related articles on the PHP Chinese website!