Solution 2: Go Generics
Let’s solve the challenge set in the previous lesson.
We'll cover the following...
Solution
Here is the reflection.go
code containing two separate functions in order to support the printing of strings using reflection and generics:
Press + to interact
package mainimport ("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()}func PrintSlice[T any](s []T) {fmt.Println("** Generics")for _, v := range s {fmt.Print(v, " ")}fmt.Println()}func PrintStringsWithReflection(strings interface{}) {fmt.Println("** Reflection for Strings")val := reflect.ValueOf(strings)if val.Kind() != reflect.Slice {return}for i := 0; i < val.Len(); i++ {element := val.Index(i).Interface()if str, ok := element.(string); ok {fmt.Print(str, " ")}}fmt.Println()}func PrintStringsWithGenerics[T any](strings []T) {fmt.Println("** Generics for Strings")// Iterate over each element in the 'strings' slicefor _, str := range strings {// Print the current element followed by a spacefmt.Print(str, " ")}// Move to the next line after printing all elementsfmt.Println()}func main() {PrintSlice([]int{1, 2, 3})PrintSlice([]string{"a", "b", "c"})PrintSlice([]float64{1.2, -2.33, 4.55})PrintReflection([]int{1, 2, 3})PrintReflection([]string{"a", "b", "c"})PrintReflection([]float64{1.2, -2.33, 4.55})PrintStringsWithReflection([]interface{}{"hello", "world"})PrintStringsWithGenerics([]string{"foo", "bar"})}
Code explanation
Let’s see the explanation of the PrintStringsWithReflection
function:
Line 30: This line defines a function named
PrintStringsWithReflection
that takes a single ...