Home >Backend Development >Golang >Are Go's Empty Interfaces or Go 1.18 Generics the True Implementation of Generic Functions?
Generic Functions in Go: A Comprehensive Guide
While exploring Go, you may encounter the concept of an empty interface. It's a powerful tool that can hold any type, requiring no additional methods.
Consider this example:
func describe(i interface{}) { fmt.Printf("Type: %T | Value: %v\n", i, i) }
When you pass different types to describe, it prints out the type and value:
"Type: int | Value: 5" // for i := 5 "Type: string | Value: test" // for i := "test"
So, is this Go's way of implementing generic functions? Not quite. Starting with Go 1.18, you can now write true generic functions. Here's an example:
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 generic function Print can handle slices of any type, offering a more versatile and type-safe approach to generic programming.
The above is the detailed content of Are Go's Empty Interfaces or Go 1.18 Generics the True Implementation of Generic Functions?. For more information, please follow other related articles on the PHP Chinese website!