To create a generic function that works with different types using reflection in Golang, you can make use of the reflect
package.
Here's an example of creating a generic function that can perform addition on different types:
package main
import (
"fmt"
"reflect"
)
func Add(a, b interface{}) interface{} {
valueOfA := reflect.ValueOf(a)
valueOfB := reflect.ValueOf(b)
switch valueOfA.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return valueOfA.Int() + valueOfB.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return valueOfA.Uint() + valueOfB.Uint()
case reflect.Float32, reflect.Float64:
return valueOfA.Float() + valueOfB.Float()
case reflect.String:
return valueOfA.String() + valueOfB.String()
default:
return nil // unsupported types
}
}
func main() {
fmt.Println(Add(5, 10)) // Output: 15
fmt.Println(Add(2.5, 3.7)) // Output: 6.2
fmt.Println(Add("Hello", "World")) // Output: HelloWorld
}
In this code, the Add
function takes two interface{} parameters, a
and b
, which can be of any type. Inside the function, the reflect
package is used to determine the kind of the provided arguments. Based on the kind, appropriate operations are performed and the result is returned as an interface{}.
Note that using reflection can result in a performance overhead, and should be used sparingly. It's generally recommended to write type-specific functions whenever possible, rather than resorting to reflection.