Advanced Go: Reflection, Generics, and Error Handling
Explore advanced concepts in Go language, including reflection, generics, and enhanced error handling:
Reflection
Reflection in Go allows you to inspect and modify the runtime type information. The reflect
package provides tools to work with reflection:
package main
import (
"fmt"
"reflect"
)
func main() {
var x float64 = 3.4
v := reflect.ValueOf(x)
fmt.Println("Type:", v.Type())
fmt.Println("Kind:", v.Kind())
fmt.Println("Value:", v.Float())
}
Generics
Go 1.18 introduces support for generics, which enables writing functions and data structures that can work with different types:
package main
import "fmt"
func PrintSlice[T any](s []T) {
for _, v := range s {
fmt.Println(v)
}
}
func main() {
intSlice := []int{1, 2, 3}
stringSlice := []string{"Hello", "Go", "Generics"}
PrintSlice[int](intSlice)
PrintSlice[string](stringSlice)
}
Error Handling
Go 1.13 introduces enhanced error handling with error wrapping and unwrapping:
package main
import (
"errors"
"fmt"
)
func main() {
err := fmt.Errorf("a new error: %w", errors.New("the root cause"))
fmt.Println(err)
var rootErr error
if errors.As(err, &rootErr) {
fmt.Println("Root error:", rootErr)
}
}
These advanced concepts help improve the versatility and flexibility of your Go code.