Search⌘ K
AI Features

Reflection vs. Generics

Explore how to handle slices in Go using reflection versus generics. Understand the differences by developing utilities that print slice elements, and observe why generics lead to simpler, cleaner code with built-in type safety compared to reflection.

We'll cover the following...

In this lesson, we’ll develop a utility that prints the elements of a slice in two ways: first, using reflection, and second, using generics.

Coding example

The code of reflection.go is as follows:

Go (1.19.0)
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, because we can’t express that in the function ...