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 reflection.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. Additionally, we have to write more code to get the desired output.
In more detail, first, we need to make sure that we are processing a slice (reflect.Slice
) and second, we have to print the slice elements using a for
loop, which...