Reflection versus generics
In this section, we develop a utility that prints the elements of a slice in two ways: first, using reflection, and second, using generics.
The code of genericsReflection.go
is as follows:
package main
import (
"fmt"
"reflect"
)
func PrintReflection(s interface{}) {
fmt.Println("** Reflection")
val := reflect.ValueOf(s)
if val.Kind() != reflect.Slice {
return
}
for i := 0; i < val.Len(); i++ {
fmt.Print(val.Index(i).Interface(), " ")
}
fmt.Println()
}
Internally, the PrintReflection()
function works with slices only. However, as we cannot express that in the function signature, we need to accept an empty interface parameter. Put simply, instead of specifying all kinds of slices, it makes much more sense to use the empty interface. Additionally, we have to write more code to get the desired output and prevent the function from crashing.
In more...